import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
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.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class HttpPostAndHeader {
public static void main(String[] args) {
HttpPostAndHeader http=new HttpPostAndHeader();
http.postHttp();
}
public void postHttp(){
// HttpPost httpPost = new HttpPost("http://localhost:6060/pingppsrv-service/PingppServlet");
HttpPost httpPost = new HttpPost("http://xxx.xxx.xxx.xx:8000");
httpPost.addHeader("Host","upcaiyun2.com");
ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
pairs.add(new BasicNameValuePair("phoneNum","phoneNum"));
pairs.add(new BasicNameValuePair("fileName","fileName"));
// pairs.add(new BasicNameValuePair("json","11111111"));
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,
30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
System.out.println(strber.toString());
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("success");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
需要用的jar commons-logging-1.1.1.jar httpclient-4.5.1.jar httpcore-4.4.4.jar
java运用HttpClient 调用http post 包含header调用
最新推荐文章于 2024-05-11 13:02:29 发布