http的get、post请求方法
package com.jov.common;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class Http {
public static String savedatabypost(String url, String user, String data) {
String result = "";
try {
// 创建连接
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// 设置参数,仿html表单提交
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("user", user));
paramList.add(new BasicNameValuePair("data", data));
post.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
// 发送HttpPost请求,并返回HttpResponse对象
HttpResponse httpResponse = httpClient.execute(post);
// 判断请求响应状态码,状态码为200表示服务端成功响应了客户端的请求
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 获取返回结果
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
System.out.println(e.toString());
}
return result;
}
public static String savedatabyget(String url, String user, String data) {
String result = "";
try {
HttpClient httpClient = new DefaultHttpClient();
// 仿地址链接直接跟参数,如:http://127.0.0.1:8080/test/test.php?name=;
HttpGet httpGet = new HttpGet(url + "?user=" + user + "&data="
+ data);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
}
return result;
}
}