import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
/**
* * 向服务器端发送数据
*
* @param url
* @param params
* @return
* @throws Exception
*/
public static String urlGetMethod(String url, String params) throws Exception {
HttpClient httpClient;
GetMethod method = null;
String responses;
if (params != null) {
// TODO 待调查
if (url.indexOf("?") < 0) {
url = url + "?";
} else {
url = url + "&";
}
url = url + URLEncoder.encode(params, "UTF-8");
}
try {
httpClient = new HttpClient();
method = new GetMethod(url);
httpClient.executeMethod(method);
responses = method.getResponseBodyAsString();//服务器返回内容,若服务器接收后没有返回内容为null
} catch (Exception e) {
throw e;
} finally {
if (method != null) {
method.releaseConnection();
}
}
return responses;
}
模拟服务端获取数据
@SuppressWarnings("serial")
public class Export extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
// 读取请求内容
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!=null){
sb.append(line);
}
String reqBody = sb.toString();
System.out.println(reqBody);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}