1. 程式人生 > >向服務器端發送數據 Get

向服務器端發送數據 Get

protect adl 獲取 println tps ext () quest serial

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);
}
}

向服務器端發送數據 Get