java net包里的方式
PrintWriter out = null;
URL httpurl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
out = new PrintWriter(httpConn.getOutputStream());
out.print(xml);
out.flush();
out.close();
Util.convertStreamToString(httpConn.getInputStream(), "GBK");
get方式
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = httpclient.execute(request);
post方式
HttpPost httpRequset = new HttpPost(url);
HttpEntity httpentity = new StringEntity(xml, "GBK");
httpRequset.setEntity(httpentity);
HttpClient httpclient = new DefaultHttpClient();
httpentity = httpclient.execute(httpRequset).getEntity();
if (httpentity != null) {
System.out.println(Util.convertStreamToString(httpentity.getContent(), "GBK"));
}
httpRequset.abort();
/**
*
* @description 转化输入流为指定编码的字符串
* @throws UnsupportedEncodingException
*/
public static String convertStreamToString(InputStream is, String charsetName)
throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,
charsetName));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
key-value键值对的post方式
// HttpPost连接对象
HttpPost httpRequset = new HttpPost("http://10.0.2.2:8080/dem/");
// 使用NameValuePair来保存要传递的Post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加要传递的参数
params.add(new BasicNameValuePair("par", "asdf"));
try {
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
// 请求httpRequset
httpRequset.setEntity(httpentity);
// 取得HttpClient
HttpClient httpClient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse = httpClient.execute(httpRequset);