急!在线等!使用java实现发送json报文的post请求方法??? 5C

急!在线等!使用java实现发送json报文的post请求方法???各位大神帮帮忙啊~~~
报文如下:
{
"busiParams": {
"serviceNum": "24027000071563"
},
"pubInfo": {
"interfaceId": "1",
"transactionId": "WEB20170707105545257737",
"interfaceType": "52",
"opId": "5010",
"countyCode": "110",
"orgId": "900000055",
"clientIP": "1",
"transactionTime": "20160512175523",
"regionCode": "110"
}
}
我的代码实现如下,这个代码是有问题的,麻烦给看看啊:

//----------------------post请求----------------------------------
public Map post(String host, int port, String path){
Map result = new HashMap();
URIBuilder builder = new URIBuilder();

        String jsonStr = "{\"busiParams\":{\"serviceNum\":\"24027000071563\"},\"pubInfo\":{\"interfaceId\":\"1\",\"transactionId\":\"WEB20170707105545257737\",\"interfaceType\":\"52\",\"opId\":\"5010\",\"countyCode\":\"110\",\"orgId\":\"900000055\",\"clientIP\":\"1\",\"transactionTime\":\"20160512175523\",\"regionCode\":\"110\"}}";   
        JSONObject jsonObject =JSONObject.parseObject(jsonStr);


        StringEntity entity = null;
        try {
            entity = new StringEntity(jsonStr);
        } catch (Exception e1) {
            e1.printStackTrace();
        }


        builder.setScheme("http");
        builder.setHost(host);
        if (port != 0){
            builder.setPort(port);
        }
        if (path != null){
            builder.setPath(path);
        }
        if (paras.size()>0){
            List<NameValuePair> pars = new ArrayList<NameValuePair>();
            for (String key : paras.keySet()) {
                pars.add(new BasicNameValuePair(key, paras.get(key)));
            }
            try {

                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");//发送json数据需要设置contentType



            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        HttpPost post;
        try {
            post = new HttpPost(builder.build());
            if(headers.size()>0){
                for (String key : headers.keySet()) {
                    post.setHeader(key, headers.get(key));
                }
            }
            if (entity!=null){

                post.setEntity(entity);
            }
            HttpResponse response = client.execute(post);
            result.put("code", String.valueOf(response.getStatusLine().getStatusCode()));
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine())!=null){
                buffer.append(line);
            }

            result.put("text", buffer.toString());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

7个回答

pom 文件依赖
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

<groupId>com.hfax</groupId>
<artifactId>csdn-learn</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>
</dependencies>

Java代码:

package com.csdn;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**

  • @date 2018-01-25 17:09
    **/
    public class HttpTool {

    /**

    • 发送post请求 *
    • @author Michael -----CSDN: http://blog.csdn.net/capmiachael
    • @param params
    • 参数
    • @param requestUrl
    • 请求地址
    • @param authorization
    • 授权书
    • @return 返回结果
    • @throws IOException
      */
      public static String sendPost(String params, String requestUrl,
      String authorization) throws IOException {

      byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为二进制流
      HttpClient httpClient = new HttpClient() {
      };// 客户端实例化
      PostMethod postMethod = new PostMethod(requestUrl);
      //设置请求头Authorization
      postMethod.setRequestHeader("Authorization", "Basic " + authorization);
      // 设置请求头 Content-Type
      postMethod.setRequestHeader("Content-Type", "application/json");
      InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
      requestBytes.length);
      RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
      requestBytes.length, "application/json; charset=utf-8"); // 请求体
      postMethod.setRequestEntity(requestEntity);
      httpClient.executeMethod(postMethod);// 执行请求
      InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
      byte[] datas = null;
      try {
      datas = readInputStream(soapResponseStream);// 从输入流中读取数据
      } catch (Exception e) {
      e.printStackTrace();
      }
      String result = new String(datas, "UTF-8");// 将二进制流转为String
      // 打印返回结果
      // System.out.println(result);

      return result;

    }

    /**

    • 从输入流中读取数据 *
    • @param inStream
    • @return
    • @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray(); outStream.close(); inStream.close(); return data; } }

测试
String responseStr = HttpTool.sendPost(jsonStr,url,"");

已经过亲自测试,没有问题

建议楼主贴程序时贴完整,方便别人查错

楼主可以看看这个库~ https://jodd.org/http/#use-the-body

给你看个简单的例子:

 /**
     * 发生http post请求
     * 
     * @param url
     * @param params
     * @param charset
     *            编码方式
     * @return
     */
    public static String doPost(String url, Map<String, String> params, ECharset charset) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String responseContent = null;

        try {
            // 创建默认的httpClient实例
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            if (ContainerUtils.isNotEmpty(params)) {
                List<NameValuePair> nameValuePairs = new ArrayList<>();
                for (String key : params.keySet()) {
                    nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset.getName()));
            }

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, charset.getName());
        } catch (Exception e) {
            logger.error("发送http post请求异常,请求url: " + url, e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                    response = null;
                }
                if (httpClient != null) {
                    httpClient.close();
                    httpClient = null;
                }
            } catch (Exception e) {
                logger.error("释放http资源异常", e);
            }
        }

        return responseContent;
    }

我的post一段JSON是这样的:
/**
* post请求
* @param url url地址
* @param jsonParam 参数
* @return
*/
public static int httpPost(String url,String jsonParam){
//post请求
DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpPost method = new HttpPost(url);

    try {
        if (null != jsonParam) {
            //解决中文乱码问题
            StringEntity entity = new StringEntity(jsonParam, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            method.setEntity(entity);
        }
        HttpResponse result = httpClient.execute(method);
        url = URLDecoder.decode(url, "UTF-8");
        /**请求发送成功,并得到响应**/
        if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String str = "";
            try {
                /**读取服务器返回过来的json字符串数据**/
                str = EntityUtils.toString(result.getEntity());
                Log.info("[" + url + ":" + str + "]");
            } catch (Exception e) {
                //logger.error("post请求提交失败:" + url, e);
                return 0;
            }
        }
        else
        {
            return 0;
        }
    } catch (IOException e) {
        Log.info(e.getMessage());
        return 0;
    }

}

用ajax发送请求就可以了

/**
* 发送xml数据请求到server端
*
* @param url
* xml请求数据地址
* @return null发送失败,否则返回响应内容
*/
public static String post(String url) {
String str=null;
StringBuffer sb=new StringBuffer();
try{
URL urll=new URL(url);
HttpURLConnection con=(HttpURLConnection)urll.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setDoInput(true);
OutputStreamWriter out=new OutputStreamWriter(con.getOutputStream());
out.flush();
out.close();
String line;
BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
while((line=in.readLine())!=null){
sb.append(line);
}
int code=con.getResponseCode();
if(code==200){
str=sb.toString();
}
else{
System.err.println("error");
}
con.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
return str;

}

你直接去搜索httpclient 例子很多的,另外你代码太乱了

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐