我是靠谱客的博主 高挑小蝴蝶,最近开发中收集的这篇文章主要介绍Android中httpUrlContent的简单使用,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

<pre name="code" class="java">package com.example.day_04_httpurlconnection;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;


public class MainActivity extends Activity {


private TextView textView;



Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {

String data = (String) msg.obj;
textView.setText(data);
};


};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = (TextView) findViewById(R.id.textView);


new Thread() {


public void run() {
getData();
};


}.start();

}


/**
* 鑱旂綉璇锋眰鏁版嵁
*/
private void getData() {
try {

//寰楀埌URL瀵硅薄,骞惰缃闂湴鍧�

URL url=new URL("http://www.baidu.com/");
//寰楀埌HttpURLConnection瀵硅薄
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//璁剧疆杩炴帴瓒呮椂
httpURLConnection.setConnectTimeout(5000);
//璁剧疆璇锋眰鏂瑰紡 get/post
httpURLConnection.setRequestMethod("POST");
//璇诲彇瓒呮椂
httpURLConnection.setReadTimeout(5000);

//姝e紡鑱旂綉
httpURLConnection.connect();
//鑾峰緱鐘舵�鐮�

int code =httpURLConnection.getResponseCode();

if(code==200){

System.out.println("联网成功");

//鑾峰彇鍖呭惈鏁版嵁鐨勮緭鍏ユ祦
InputStream inputStream = httpURLConnection.getInputStream();

BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
//璁板綍姣忎竴琛岃鍙栫殑鏁版嵁
String data;
//鎷兼帴瀛楃涓�

StringBuffer stringBuffer=new StringBuffer();
while ((data=bufferedReader.readLine())!=null) {
stringBuffer.append(data);
}


/* System.out.println(stringBuffer.toString());

textView.setText(stringBuffer.toString());*/

Message msg = Message.obtain();
msg.obj=stringBuffer.toString();
handler.sendMessage(msg);

}else{

System.out.println("联网失败");

}




} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}






}


 

最后

以上就是高挑小蝴蝶为你收集整理的Android中httpUrlContent的简单使用的全部内容,希望文章能够帮你解决Android中httpUrlContent的简单使用所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部