java "application/json" 3个例子,懒

    /**
    * java.net
    * application/json
    * @param strURL
    * @param params
    * @return
    */
public static String jsonNetPost(String strURL, String params) {
      try {
         // 创建连接
         URL url = new URL(strURL);
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setDoOutput(true);
         connection.setDoInput(true);
         connection.setUseCaches(false);
         connection.setInstanceFollowRedirects(true);
         // 设置请求方式
         connection.setRequestMethod("POST");
         // 设置接收数据的格式
         connection.setRequestProperty("Accept", "application/json");
         // 设置发送数据的格式
         connection.setRequestProperty("Content-Type", "application/json");
         // utf-8编码
         connection.connect();
         OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
         out.append(params);
         out.flush();
         out.close();
         // 读取响应
         // 获取长度
         int length = (int) connection.getContentLength();
         InputStream is = connection.getInputStream();
         if (length != -1) {
            byte[] data = new byte[length];
            byte[] temp = new byte[512];
            int readLen = 0;
            int destPos = 0;
            while ((readLen = is.read(temp)) > 0) {
               System.arraycopy(temp, 0, data, destPos, readLen);
               destPos += readLen;
            }
            String result = new String(data, "UTF-8"); // utf-8编码
            return result;
         }
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   // 自定义错误信息
      return "请求失败";
   }

/**
 * httpclient3 jsonPost
 * @param strURL
 * @param map
 * @return
 */
public static String jsonPostC3(String strURL, Map<String,Object> map ) {
   String returnStr ="";
   try {
      PostMethod method = new PostMethod(strURL);


      ObjectMapper mapper = new ObjectMapper();
      StringWriter sw = new StringWriter();
      JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
      mapper.writeValue(gen, map);
      gen.close();
      String dataStr = sw.toString();
      byte[] b = dataStr.getBytes("utf-8");
      InputStream is = new ByteArrayInputStream(b, 0, b.length);
      RequestEntity re = new InputStreamRequestEntity(is, b.length,
            "application/json;charset=utf-8");
      method.setRequestEntity(re);
      //System.out.println(dataStr);
      org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
      int state = httpClient.executeMethod(method);
      //System.out.println(state+"<-----state");
      if(state == 200){
         //System.out.println(method.getResponseBodyAsString()+"<-wxSendResult");
      }
      //returnStr =method.getResponseBodyAsString();
      byte[] data =method.getResponseBody();
      // utf-8编码
      returnStr = new String(data, "UTF-8");
   } catch (Exception e) {
      e.printStackTrace();
   }
   return returnStr;
}

/**
 * httpclient4 jsonPost
 * @param url
 * @param params
 * @param charset
 * @param connectionTimeout
 * @param soTimeout
 * @return
 */
public static String jsonPost(String url, Map<String,Object> params,String charset,Integer connectionTimeout,Integer soTimeout) {
   HttpClient hc = new DefaultHttpClient();
   String body = null;
   try {
      // Post请求
      HttpPost httppost = new HttpPost(url);
      // 设置参数
      if(connectionTimeout!=null){
         HttpConnectionParams.setConnectionTimeout(httppost.getParams(), connectionTimeout);
      }
      if(soTimeout!=null){
         HttpConnectionParams.setSoTimeout(httppost.getParams(), soTimeout);
      }
      StringEntity strEntity =new StringEntity(JSONObject.fromObject(params).toString(),charset );

      strEntity.setContentEncoding(charset);
      strEntity.setContentType("application/json");
      httppost.setEntity(strEntity);
      // 发送请求
      HttpResponse httpresponse = hc.execute(httppost);
      // 获取返回数据
      HttpEntity entity = httpresponse.getEntity();
      //body = EntityUtils.toString(entity);
      byte[] data =EntityUtils.toByteArray(entity);
      // utf-8编码
      body = new String(data, charset);
      EntityUtils.consume(entity);
   } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
   } catch (ClientProtocolException e) {
      e.printStackTrace();
   } catch (ParseException e) {
      e.printStackTrace();
   } catch (IOException e) {
      e.printStackTrace();
   }finally {
      try { hc.getConnectionManager().shutdown(); } catch (Exception ignore) {}
   }
   return body;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值