post get 请求 模板

来源:互联网 发布:石家庄数控编程招聘 编辑:程序博客网 时间:2024/05/07 22:55
//线程加载
Runnable runable = new Runnable() {


@Override
public void run() {


String dataByUrl = HttpConnection.request_Detail("你的请求地址URL");
Message message = Message.obtain();
message.obj = dataByUrl;
handler.sendMessage(message);
}
};






Handler handler = new Handler() {


public void handleMessage(Message msg) {


if (msg.obj != null) {
String data=msg.obj.toString();

}


};
};




//你自己重新建个包把这个方法放到包下,get,post都可以,通用


/**

* httpClent post

* @param url
* @return
*/
public static String httpClientPost(String url) {
HttpPost post = new HttpPost(url);
HttpClient mClient = new DefaultHttpClient();
// 数据传输
List<NameValuePair> list = new ArrayList<NameValuePair>();


try {
HttpEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
// 设置传输内容
post.setEntity(entity);
HttpResponse response = mClient.execute(post);
HttpEntity mEntity = response.getEntity();
InputStream stream = mEntity.getContent();
return froatStream(stream);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


return null;
}


/**

* 字节流转换

* @param mInputStream
* @return
*/
public static String froatStream(InputStream mInputStream) {
// 转换成String
byte[] buffer = new byte[1024];
int len = 0;
StringBuffer sb = new StringBuffer();
try {
while ((len = mInputStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len, "UTF-8"));
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


/**

* httpclient 请求

* @param url
* @return
*/
public static String httpClientGet(String url) {
// 创建一个连接对象
HttpGet hGet = new HttpGet(url);
// 创建一个httpClient 对象
HttpClient mClient = new DefaultHttpClient();
InputStream stream = null;
// 执行请求
try {
HttpResponse mHttpResponse = mClient.execute(hGet);
// 获取返回的数据
HttpEntity entity = mHttpResponse.getEntity();
stream = entity.getContent();
return froatStream(stream);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();


}


return null;
}
0 0
原创粉丝点击