Android post get 请求 模板

释放双眼,带上耳机,听听看~!
//线程加载
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;
}

 

人已赞赏
Android文章

compileDebugJavaWithJavac.compileSdkVersion 'android-24' requires JDK 1.8 or later to compile.

2020-3-28 11:48:01

Android文章

Android ViewPager使用详解

2020-3-28 13:03:31

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索