HttpURLConnection和okHttp如何获取网络数据-创新互联
这篇文章给大家分享的是有关HttpURLConnection和okHttp如何获取网络数据的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
成都创新互联长期为上千余家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为漳平企业提供专业的成都做网站、成都网站制作,漳平网站改版等技术服务。拥有10年丰富建站经验和众多成功案例,为您定制开发。代码示例
xml如下:
activity如下:
public class NetActivity extends AppCompatActivity implements View.OnClickListener{ private Button http,okhttp; private TextView stringData; private String web="https://www.baidu.com"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_net); http= (Button) findViewById(R.id.http); okhttp= (Button) findViewById(R.id.okhttp); stringData= (TextView) findViewById(R.id.stringData); http.setOnClickListener(this); okhttp.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.http: sendRequestWithHttpURLConnection(); break; case R.id.okhttp: sendRequestWithokHttp(); break; } } private void sendRequestWithHttpURLConnection(){ new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection=null; BufferedReader reader=null; try { URL url=new URL(web); connection= (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); InputStream in=connection.getInputStream(); reader=new BufferedReader(new InputStreamReader(in)); StringBuffer response=new StringBuffer(); String line; while ((line=reader.readLine())!=null){ response.append(line); } showRespond(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (reader!=null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }).start(); } private void showRespond(final String response) { runOnUiThread(new Runnable() { @Override public void run() { stringData.setText(response); } }); } private void sendRequestWithokHttp(){ new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder() .url(web).build(); Response response=client.newCall(request).execute(); String str=response.body().string(); showRespond(str); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }
注意:需要在加权限
1.
2.okhttp3需要在gradle添加依赖
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.android.support:design:24.2.1' compile 'com.squareup.okhttp3:okhttp:3.4.1'//依赖 testCompile 'junit:junit:4.12' }
感谢各位的阅读!关于“HttpURLConnection和okHttp如何获取网络数据”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
名称栏目:HttpURLConnection和okHttp如何获取网络数据-创新互联
文章转载:http://hbruida.cn/article/dcdsoe.html