请求http地址

/**
  * 
  * @param url
  * @param body
  * @return
  */
 public static String post(String url,String body,String contentType,String charset){
  if (url == null || StringUtils.isEmpty(url)) {
   return null;
  }
  HttpClientBuilder clientBuilder=HttpClientBuilder.create();
  CloseableHttpClient httpClient=clientBuilder.build();
  HttpPost post=new HttpPost(url);
  //post.addHeader("Content-Type", contentType);
  //post.addHeader("Content-Length", body.length()+"");
  HttpResponse resp=null;
  String respStr="";
  try {
   StringEntity entity=new StringEntity(body,ContentType.create(contentType,charset));
   post.setEntity(entity);
   resp=httpClient.execute(post);
   HttpEntity respentity =resp.getEntity();
   respStr=EntityUtils.toString(respentity,"UTF-8");
  
  } catch (Exception e) {   
   e.printStackTrace();
  }finally{
   try {
    httpClient.close();
   } catch (IOException e) {
    
    e.printStackTrace();
   }
  }
  
  return respStr;
 }

 

 

 public static void main(String args[]){
//  String body="{\"accountId\":\"aaaxxdrtte32we\",\"sign\":\"erwsWESwsLokiuj6ikOIU98o080UIIYyjj\",\"appId\":\"abcdefghijklmnoprtewwwqwxyz123456\",\"callId\":\"20150603131434987\",\"captchaCode\":\"8792\",\"playTimes\":\"2\","
//    +"\"to\":\"13683382281\",\"displayNum\":\"125904030106\",\"respUrl\":\"http://172.16.10.34:8080/calls/respurl.xt\",\"userData\":\"2015002349\"}";
  String body="<?xml version='1.0' encoding='utf-8'?><voicecapctha><accountId>aaaxxdrtte32we</accountId><sign>erwsWESwsLokiuj6ikOIU98o080UIIYyjj</sign><appId>abcdefghijklmnoprtewwwqwxyz123456</appId><callId>20150603131434987</callId><capcthaCode>8792</capcthaCode><playTimes>2</playTimes> "
    +"<to>13683382281</to><displayNum>125904030106</displayNum> <respUrl>http://118.194.243.239:8881/2013-12-26/Calls/voiceCapctha</respUrl>  <userData>2015002349</userData></voicecapctha>";
  String url="http://183.207.212.144:8080/calls/voiceCaptcha.xt";
//  String contentType="application/json";
  String contentType="application/xml";
  String charset="UTF-8";
  String result=post(url,body,contentType,charset);
  System.out.println(result);
 }

猜你喜欢

转载自songywlanna.iteye.com/blog/2219225