Created
December 2, 2014 09:23
-
-
Save kaka2008/cb834b687ddb9e9ebec2 to your computer and use it in GitHub Desktop.
使用httpclient调用post方式api,post时,直接传递一个json
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 org.apache.http.HttpEntity; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.StatusLine; | |
import org.apache.http.client.ClientProtocolException; | |
import org.apache.http.client.HttpClient; | |
import org.apache.http.client.methods.HttpPost; | |
import org.apache.http.entity.StringEntity; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.util.EntityUtils; | |
/** | |
* 调用post方法,传输json内容 | |
* | |
* @author weizhankui | |
* | |
*/ | |
public class PostJsonExample { | |
public static void visitPostUrl() throws ClientProtocolException, | |
IOException { | |
HttpClient httpclient = new DefaultHttpClient(); | |
HttpPost httppost = new HttpPost( | |
"http://localhost:8080/msg/testjson?apikey=apikey"); | |
String jsonStr = "{\"name\":\"张三\",\"add\":\"北京市朝阳区\"}"; | |
// 传json,并设置编码 | |
httppost.setEntity(new StringEntity(jsonStr, "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