Created
December 2, 2014 09:21
-
-
Save kaka2008/fe767b218bc7e4b4b710 to your computer and use it in GitHub Desktop.
使用httpclient调用get方式的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.net.URLEncoder; | |
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.HttpGet; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.util.EntityUtils; | |
/** | |
* 调用get类型的接口,获取参数 | |
* | |
* @author weizhankui | |
* | |
*/ | |
public class GetExample { | |
public static void visitGetUrl() throws ClientProtocolException, | |
IOException { | |
HttpClient client = new DefaultHttpClient(); | |
// 编码 | |
String str = URLEncoder.encode("啊啊啊", "utf-8"); | |
HttpGet get = new HttpGet("http://localhost:8080/msg/testget/" + str | |
+ "?apikey=apikey"); | |
HttpResponse response = client.execute(get); | |
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 { | |
visitGetUrl(); | |
} 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