Java uses Apache httpclient to send post requests __java

Source: Internet
Author: User

Original address: http://www.pocketdigi.com/20110521/294.html


Import java.io.UnsupportedEncodingException;
Import java.util.ArrayList;
Import java.util.List;

Import Org.apache.http.HttpResponse;
Import Org.apache.http.NameValuePair;
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.protocol.HTTP;
Import Org.apache.http.util.EntityUtils;
/**
*JDK default no Org.apache.http package, need to go to http://hc.apache.org/downloads.cgi download first
* Download HttpClient, unzip, import all jars in eclipse
*/
public class TT {
/**
* @param args
* @throws unsupportedencodingexception
* This example, in order to simplify the point, did not catch the exception, directly at the program entrance added exception to throw the declaration
*/
public static void Main (string[] args) throws Exception {
TODO auto-generated Method Stub
String url= "http://localhost/newspaper/test/1.php";
Post's URL
HttpPost httppost=new httppost (URL);
Create a HttpPost object
List<namevaluepair> params=new arraylist<namevaluepair> ();
Create a Namevaluepair array to store the parameters to be transmitted
Params.add (New Basicnamevaluepair ("pwd", "2544"));
Add parameters
Httppost.setentity (New Urlencodedformentity (params,http). Utf_8));
Set encoding
HttpResponse response=new defaulthttpclient (). Execute (httppost);
Sends a post, and returns a HttpResponse object
if (Response.getstatusline (). Getstatuscode () ==200) {//If the status code is 200, the return is normal
String result=entityutils.tostring (Response.getentity ());
Get the returned string
SYSTEM.OUT.PRINTLN (result);
Print output
}
}
}

Processing garbled, the result string obtained by the conversion,

Result=new String (result.getbytes ("iso-8859-1"), "GBK")


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.