如何在java中发送post请求
2个回答
展开全部
package com.test;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class D {
public static void main(String[] args){
List<NameValuePair> nvps= new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("id", "1"));
String url="https://www.hao123.com/";
HttpClient httpClient = null;
String response="";
try {
HttpPost post = new HttpPost(url);
post.setHeader("Connection", "close");
httpClient = new DefaultHttpClient();
post.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse httpres= httpClient.execute(post);
if (httpres.getStatusLine().getStatusCode() >= 300) {
System.out.println("Request Failed,Code:" + httpres.getStatusLine().getStatusCode() + ",URL:" + url);
}
response = EntityUtils.toString(httpres.getEntity(), "utf-8");
}catch(Exception e){
e.printStackTrace();
}finally{
if(httpClient!=null){
httpClient.getConnectionManager().shutdown();
}
}
System.out.println(response);
}
}
需要httpclient-4.1.3.jar,httpcore-4.1.4.jar和commons-logging-1.1.1.jar
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class D {
public static void main(String[] args){
List<NameValuePair> nvps= new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("id", "1"));
String url="https://www.hao123.com/";
HttpClient httpClient = null;
String response="";
try {
HttpPost post = new HttpPost(url);
post.setHeader("Connection", "close");
httpClient = new DefaultHttpClient();
post.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse httpres= httpClient.execute(post);
if (httpres.getStatusLine().getStatusCode() >= 300) {
System.out.println("Request Failed,Code:" + httpres.getStatusLine().getStatusCode() + ",URL:" + url);
}
response = EntityUtils.toString(httpres.getEntity(), "utf-8");
}catch(Exception e){
e.printStackTrace();
}finally{
if(httpClient!=null){
httpClient.getConnectionManager().shutdown();
}
}
System.out.println(response);
}
}
需要httpclient-4.1.3.jar,httpcore-4.1.4.jar和commons-logging-1.1.1.jar
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询