目前我正在研究github api。 尝试使用Apache HTTP API将我的身份验证令牌作为参数发送一个简单的http GET时, 控制台抛出这个:
Exception in thread "main" org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
at xyz.lexium.giapb.http.GIAPBHttp.sendGet(GIAPBHttp.java:25)
at xyz.lexium.giapb.GIAPB.main(GIAPB.java:12)
Caused by: org.apache.http.ProtocolException: Target host is not specified
at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:70)
at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:124)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:183)
... 4 more
这是我目前的代码:
package xyz.lexium.giapb.http;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class GIAPBHttp {
public static final String baseUrl = "https://api.github.com";
private static final String USER_AGENT = "Mozilla/5.0";
// HTTP GET request
public static void sendGet() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("baseUrl");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// responce
EntityUtils.consume(entity1);
} finally {
response1.close();
}
HttpPost httpPost = new HttpPost(baseUrl);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("access_token", "cant_steal_this_(dododododo)"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// responce
EntityUtils.consume(entity2);
} finally {
response2.close();
}
}
}
是的,我已经阅读了其他相关问题。但我修改了它。这是一个完整的URL,所以其他人不要帮助
答案 0 :(得分:3)
第25行
HttpGet httpGet = new HttpGet("baseUrl");
应该是
HttpGet httpGet = new HttpGet(baseUrl);
答案 1 :(得分:1)
您正尝试使用httpclient访问HTTPS
资源。这导致协议错误。
访问https网址需要更多工作,如此处所述 - Ignoring SSL certificate in Apache HttpClient 4.3