案例1:
- import org.apache.commons.httpclient.*;
- import org.apache.commons.httpclient.methods.*;
- import org.apache.commons.httpclient.params.HttpMethodParams;
- import java.io.*;
- public class HttpClientTutorial {
- private static String url = "http://10.129.39.149:8090/ajax/loginMgt/login.action";
- public static void method(HttpClient client,String url,String body){
- PostMethod method = new PostMethod(url);
- //"count":10,"ignoreCase":"false","paras":["a%"],"queryId":"getMenu"
- NameValuePair[] postData = new NameValuePair[]{};
- //postData[0] = new NameValuePair("count", 10);
- method.setRequestBody(body);//addParameters(postData);
- // Provide custom retry handler is necessary
- /*method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
- new DefaultHttpMethodRetryHandler(3, false));*/
- try {
- // Execute the method.
- int statusCode = client.executeMethod(method);
- if (statusCode != HttpStatus.SC_OK) {
- System.err.println("Method failed: " + method.getStatusLine());
- }
- // Read the response body.
- byte[] responseBody = method.getResponseBody();
- // Deal with the response.
- // Use caution: ensure correct character encoding and is not binary data
- System.out.println(new String(responseBody,"utf-8"));
- } catch (HttpException e) {
- System.err.println("Fatal protocol violation: " + e.getMessage());
- e.printStackTrace();
- } catch (IOException e) {
- System.err.println("Fatal transport error: " + e.getMessage());
- e.printStackTrace();
- } finally {
- // Release the connection.
- method.releaseConnection();
- }
- }
- public static void main(String[] args) {
- // Create an instance of HttpClient.
- HttpClient client = new HttpClient();
- String body ="[{\"userId\":1,\"password\":1}]";
- // Create a method instance.
- method(client,url,body);
- url = "http://10.129.39.149:8090/ajax/getInitValueArr.action";
- body = "[{\"count\":10,\"ignoreCase\":\"false\",\"paras\":[\"a%\"],\"queryId\":\"getMenu\"}]";
- method(client,url,body);
- }
- }
案例2:
- HttpClient c = new HttpClient();
- HttpMethod m = new GetMethod();
- String path =msnListPath+"?account="+userSimpleInfo.getMsnAccount()+"&type=msn&uid="+userSimpleInfo.getPassportId()+"&pwd="+userSimpleInfo.getMsnPassword();
- m.setPath(path);
- String response="";
- int status = 0;
- try {
- status = c.executeMethod(m);
- if(status == HttpStatus.SC_OK) {
- byte[] rbytes = m.getResponseBody();
- response = new String(rbytes,"UTF-8");
- return response;
- }
- } catch (HttpException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return "error";