java 后台构造http转发请求

public void request(String requestUri, String msg) throws IOException
{
// 设置请求参数
String url = requestUri;

// 1、构造http请求包
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 1000 * 60 * 60);
HttpConnectionParams.setSoTimeout(httpParams, 1000 * 60 * 60);
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpHost target = new HttpHost(HOST_NAME, HTTP_PORT, "http");
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/x-www-form-urlencoded"); // 必须设置成该方式

List params = new ArrayList();
params.add(new BasicNameValuePair(REQ_MSG_NAME, msg));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // UrlEncodedFormEntity

// 2、发送http请求
HttpResponse response = httpClient.execute(target, httppost);

// 3、响应校验
HttpEntity resEntity = response.getEntity();

if (HttpURLConnection.HTTP_OK == response.getStatusLine()
.getStatusCode())
{
GeneralHttpResponse result = null;
if (resEntity != null)
{
BufferedReader br = new BufferedReader(new InputStreamReader(
resEntity.getContent()));
String rt = "";
String line = "";
while ((line = br.readLine()) != null)
{
rt = rt + "\r\n" + line;
}
rt = new String(rt.getBytes(), HTTP.UTF_8);
result = new GeneralHttpResponse(rt);
br.close();
EntityUtils.consume(resEntity);
}


if (!result.isSuccess())
{
throw new RuntimeException(
"Rquest client info failed on url [ " + url
+ "],  " + result.getErrors());
}
}
else
{
throw new IOException("Communication with uri: "
+ response.getStatusLine());
}
}

你可能感兴趣的:(Java技术)