Android代码工具集——网络Post请求

/**
	 * 
	 * @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();  
    }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值