转自:http://username2.iteye.com/blog/1664995
public static String method1() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
// // 代理的设置
// HttpHost proxy = new HttpHost("10.60.8.20", 8080);
// httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
// 目标地址
HttpPost httppost = new HttpPost("http://localhost/user/user_saveUser.action");
System.out.println("请求: " + httppost.getRequestLine());
// // 构造最简单的字符串数据
// StringEntity reqEntity = new StringEntity("username=test&password=test");
// // 设置类型
// reqEntity.setContentType("application/x-www-form-urlencoded");
// // 设置请求的数据
// httppost.setEntity(reqEntity);
//post 参数 传递
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("content", lectureContent )); //参数
nvps.add(new BasicNameValuePair("path", "D:/file")); //参数
nvps.add(new BasicNameValuePair("name", "8")); //参数
nvps.add(new BasicNameValuePair("age", "9")); //参数
nvps.add(new BasicNameValuePair("username", "wzt")); //参数
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); //设置参数给Post
// 执行
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
// 显示结果
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
if (entity != null) {
entity.consumeContent();
}
return null;
}
/** 模拟url访问
* 从特定的url中获取json
* @param urlStr
* @param params
* @return
* json object ,or null if failed
*/
private static JSONObject getJsonFromUrl(String urlStr,
Map<String, String> params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlStr);
JSONObject json = null;
try {
if (params != null) {
Iterator<String> keys = params.keySet().iterator();
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
while (keys.hasNext()) {
String key = keys.next();
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
}
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
byte[] bytes = new byte[256];
StringBuffer sb = new StringBuffer();
while (is.read(bytes) > 0) {
sb.append(new String(bytes));
bytes = new byte[256];
}
json = JSONObject.fromObject(sb.toString());
} catch (Exception e) {
log.error("http client execute error:" + e.getMessage(), e);
}
return json;
}