Created
December 2, 2014 09:21
-
-
Save kaka2008/654b0d63a4c9e5b2b5b0 to your computer and use it in GitHub Desktop.
使用httpclient 调用post方式api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package client; | |
import java.io.IOException; | |
import java.nio.charset.Charset; | |
import java.util.ArrayList; | |
import java.util.List; | |
import org.apache.http.Consts; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.StatusLine; | |
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.util.EntityUtils; | |
/** | |
* 调用post方式的接口,获取参数 | |
* | |
* @author weizhankui | |
* | |
*/ | |
public class PostExample { | |
public static void visitPostUrl() throws ClientProtocolException, | |
IOException { | |
HttpClient httpclient = new DefaultHttpClient(); | |
HttpPost httppost = new HttpPost( | |
"http://localhost:8080/msg/test?apikey=apikey"); | |
// 参数 | |
List<NameValuePair> nvps = new ArrayList<NameValuePair>(); | |
nvps.add(new BasicNameValuePair("uid", "这是uid")); | |
nvps.add(new BasicNameValuePair("type", "这是类型")); | |
// 设置编码 | |
httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); | |
System.out.println("执行: " + httppost.getRequestLine()); | |
HttpResponse response = httpclient.execute(httppost); | |
HttpEntity resEntity = response.getEntity(); | |
// 返回状态码 | |
StatusLine statusLine = response.getStatusLine(); | |
if (statusLine.getStatusCode() >= 300) { | |
System.out.println("出错了" + statusLine.getReasonPhrase()); | |
} | |
// 返回值 | |
if (resEntity != null) { | |
System.out.println(new String(EntityUtils.toByteArray(resEntity), | |
Charset.forName("utf-8"))); | |
} | |
} | |
public static void main(String[] args) { | |
try { | |
visitPostUrl(); | |
} catch (ClientProtocolException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment