/**
*
* @param url 访问url地址
* @param json 传递的json
* @param encoding 编码格式
* @return
*/
public static String postJsonData(String url, String json, String encoding) {
System.out.println(url+"请求参数:"+json);
HttpParams httpParams = new BasicHttpParams();
// 设置连接超时时间(单位毫秒)
HttpConnectionParams.setConnectionTimeout(httpParams, 10*1000);
// 设置读数据超时时间(单位毫秒)
HttpConnectionParams.setSoTimeout(httpParams, 10*1000);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
String result = "";
InputStream is = null ;
try {
StringEntity entity = new StringEntity(json,encoding);
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
is = response.getEntity().getContent();
result =new String(readInStream(is),encoding);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
client.getConnectionManager().shutdown(); //必须关闭连接
}
System.out.println(url+"返回结果:"+result);
return result;
}
//将输入流转换成字节数组
private static byte[] readInStream(InputStream is) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = -1;
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
return baos.toByteArray();
}
Android代码工具集——网络Post请求
最新推荐文章于 2023-05-21 16:25:53 发布