java HttpClient 后端模拟ajax 请求
提示:直接上代码
代码如下(示例):
public static String httpPost(String url,String arg){
InputStream is;
BufferedReader br;
StringBuilder sBuilder = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url");
//方式一:将参数添加到请求体当中
httpPost.setEntity(new StringEntity(arg,"utf-8"));//默认是采用ISO-8859-1 对于中文需要使用utf-8编码
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
httpPost.setHeader("X-Requested-With","xmlhttprequest");
httpPost.setHeader("Access-Control-Allow-Origin","*");
httpPost.setHeader("Access-Control-Allow-Credentials","true");
//方式二: 如果需要传递多个参数
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("key","value"));
parameters.add(new BasicNameValuePair("key","value"));
parameters.add(new BasicNameValuePair("key","value"));
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse httpResponse = httpClient.execute(httpPost);
//连接成功
if(200 == httpResponse.getStatusLine().getStatusCode()) {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
br = new BufferedReader(new InputStreamReader(is));
String tempStr;
sBuilder = new StringBuilder();
while ((tempStr = br.readLine()) != null) {
sBuilder.append(tempStr);
}
br.close();
is.close();
}
}catch(Exception e){
e.printStackTrace();
}
return sBuilder==null? "":sBuilder.toString();
}