美文网首页
2020-01-07

2020-01-07

作者: IT码农锋 | 来源:发表于2020-01-07 10:27 被阅读0次

Java 网络post请求参数为JSON 格式处理

   前段时间因为业务上对接第三方接口 ,而接口参数入参是json格式,在调用过程中出现参数乱码问题处理,与大家分一下:

Java代码实现如下:

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * post请求
 * @param url
 * @param jsonParams
 * @return
 */
public static String doSendPostRequest(String url, String jsonParams){
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    String response = null;
    try {
        StringEntity s = new StringEntity(jsonParams,"utf-8");
        s.setContentType("application/json;charset=utf-8");//发送json数据需要设置contentType
        post.setEntity(s);
        HttpResponse res = client.execute(post);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(res.getEntity());// 返回json格式:
            response = result;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return response;
}

//请求具体请求如下:
public static void main(String[] args) throws IOException {
String resultStr = "{'Id':'1222' ,'lade': '7759'}";
String url = "xxxxxxxxxxxx.com";
resultStr = RequestUtil.doSendPostRequest(url,resultStr);
System.out.println(resultStr);
}

注意:String格式的jsonParams实例化转为StringEntity时,需要加上utf-8 编码,不然传入的参数会乱码,导致调用报错。

相关文章

网友评论

      本文标题:2020-01-07

      本文链接:https://www.haomeiwen.com/subject/locractx.html