java客户端请求http post方式,参数放到body体中,json字符串的方式

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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;```

public static JSONObject test(String url, Double lat, Double lon, Integer level) {
String data = "[{“lng”: " + lon + ",“lat”: " + lat + ",“level”: " + level + “}]”;
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(data);
s.setContentEncoding(“UTF-8”);
s.setContentType(“application/json”);//发送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 = JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}

    if (response==null){
        System.out.println("no data");
    }else{
        System.out.println(response.toString());
    }

    return response;


}

你可能感兴趣的:(java客户端请求http post方式,参数放到body体中,json字符串的方式)