指定url发起请求并获取同步应答

来源:互联网 发布:极致追击 知乎 编辑:程序博客网 时间:2024/06/07 05:46
String postUrl = "";//根据需要指定相应的urlHttpClient client = new HttpClient();PostMethod method = new PostMethod(postUrl);NameValuePair[] pair = {new NameValuePair("customerId",customerId),new NameValuePair("reqStr",reqStr)};method.setRequestBody(pair);client.getHttpConnectionManager().getParams().setConnectionTimeout(20000);int statusCode = client.executeMethod(method);if(statusCode != 200){out.println("httpClient.executeMethod error. statusCode is "+statusCode);return;}StringBuffer retStr = new StringBuffer();InputStreamReader insr = new InputStreamReader(method.getResponseBodyAsStream());int respInt = insr.read();while(respInt != -1){retStr.append(String.valueOf((char)respInt));respInt = insr.read();}out.println(retStr.toString());
其中NameValuePair[]用于配置发起请求时需要的参数。程序需要使用到apache的HttpClient.jar包,读者可自行下载。
原创粉丝点击