我成功地使用这段代码通过GET方法发送带有一些参数的HTTP请求
void sendRequest(String request)
{
// i.e.: request = "http://example.com/index.php?param1=a¶m2=b¶m3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
}
现在我可能需要通过POST方法发送参数(即param1, param2, param3),因为它们非常长。
我想添加一个额外的参数,该方法(即字符串httpMethod)。
我怎样才能尽可能少地更改上面的代码,以便能够通过GET或POST发送参数?
我希望情况会有所改变
connection.setRequestMethod("GET");
to
connection.setRequestMethod("POST");
可以完成这个任务,但是参数仍然通过GET方法发送。
HttpURLConnection有任何方法可以帮助吗?
有什么有用的Java构造吗?
任何帮助都将不胜感激。
我强烈推荐构建在apache http api上的http-request。
对于你的案例,你可以看到例子:
private static final HttpRequest<String.class> HTTP_REQUEST =
HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer())
.build();
public void sendRequest(String request){
String parameters = request.split("\\?")[1];
ResponseHandler<String> responseHandler =
HTTP_REQUEST.executeWithQuery(parameters);
System.out.println(responseHandler.getStatusCode());
System.out.println(responseHandler.get()); //prints response body
}
如果您对响应体不感兴趣
private static final HttpRequest<?> HTTP_REQUEST =
HttpRequestBuilder.createPost("http://example.com/index.php").build();
public void sendRequest(String request){
ResponseHandler<String> responseHandler =
HTTP_REQUEST.executeWithQuery(parameters);
}
对于一般发送post请求与HTTP -request:阅读文档,看到我的答案HTTP post请求与JSON字符串在JAVA,发送HTTP post请求在JAVA, HTTP post使用JSON在JAVA
GET和POST方法设置如下…两种类型的api调用1)get()和2)post()。Get()方法从API json数组中获取值& post()方法在url中的数据post中使用并获得响应。
public class HttpClientForExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpClientExample http = new HttpClientExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://www.google.com/search?q=developer";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
urlParameters.add(new BasicNameValuePair("cn", ""));
urlParameters.add(new BasicNameValuePair("locale", ""));
urlParameters.add(new BasicNameValuePair("caller", ""));
urlParameters.add(new BasicNameValuePair("num", "12345"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
}