如何用java模拟ajax数据发送请求

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

案例1:

import org.apache.commons.httpclient.*;

import org.apache.commons.httpclient.methods.*;

import org.apache.commons.httpclient.params.HttpMethodParams;

importjava.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";

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航