[Java] httpPost and httpGet example

熱門文章 (Popular Post)

Posted by : Duran Hsieh 2012-11-06


jar: 
org.apache.commons.logging-1.1.1.jar
httpclient-4.2.2.jar
httpcpre-4.2.2.jar

download link: http://hc.apache.org/downloads.cgi



---------

package Test;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class Test {
public static void main(String[] args) throws Exception{
//GET method
DefaultHttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet("http://");

HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();

System.out.println("Response Status: " + response.getStatusLine());

//POST method
HttpPost httpost = new HttpPost("http://");
httpclient.execute(httpost);

List <namevaluepair>  nvps = new ArrayList&lt <namevaluepair>();
nvps.add(new BasicNameValuePair("userId", "username"));
nvps.add(new BasicNameValuePair("password", "password"));

httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

response = httpclient.execute(httpost);
entity = response.getEntity();

System.out.println("Response Status: " + response.getStatusLine());

}
---------


--
如果覺得文章不錯,請幫忙點選廣告,
謝謝!


Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Duran Hsieh @ Duran 的技術冶煉廠 - Date A Live - Powered by Blogger - Designed by Johanes Djogan -