java 将请求数据(可能是对象或者是json)处理成String类型,然后传给目标路径,获取到对方的响应,回传数据为String类型
- 可以通过
com.alibaba.fastjson
中的工具实现将String和json数据的处理
/**
* 连接工具POST
* @param urlStr 请求路径
* @param reqStr 请求参数 String
* @return
*/
public static String httpPost(String urlStr,String reqStr){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlStr);
post.setHeader("Content-Type", "application/json");
String respStr = "";
try{
StringEntity s = new StringEntity(reqStr, ContentType.APPLICATION_JSON);
s.setContentEncoding("UTF-8");
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
strber.append(line + "\n");
}
inStream.close();
respStr = strber.toString();
}catch(Exception e){
throw new RuntimeException(e);
}
return respStr;
}