[英]Getting org.apache.http.client.ClientProtocolException while calling AlchemyAPI
我在使用Apache HttpClient調用AlchemyAPI
for TextGetTargetedSentiment
時遇到org.apache.http.client.ClientProtocolException
:
org.apache.http.ProtocolException:服務器無法通過有效的HTTP響應進行響應
下面是代碼片段。
URI uri = new URIBuilder()
.setScheme("http")
.setHost("access.alchemyapi.com/calls/text/TextGetTargetedSentiment")
.setParameter("apikey", <api-key>)
.setParameter("outputMode", "json")
.setParameter("showSourceText", "0")
.setParameter("target", <target>)
.setParameter("text", <news article>)
.build();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);
// add header
post.setHeader("User-Agent", <user agent>);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
謝謝你的幫助。
我懷疑您用於目標和文本的值可能有些奇怪,這可能會使事情搞砸。 如果此示例無法說明問題,請發送電子郵件至questions@alchemyapi.com,以獲得更多支持。 以下對我有用:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class Main {
public static void main(String[] args) {
try
{
HttpClient client = new DefaultHttpClient();
String text = "Text analytics is fun with AlchemyAPI.";
String API_KEY = ""; // Add your API key here
URI uri = new URIBuilder()
.setScheme("http")
.setHost("access.alchemyapi.com/calls/text/TextGetTargetedSentiment")
.setParameter("apikey", API_KEY)
.setParameter("outputMode", "json")
.setParameter("showSourceText", "1")
.setParameter("target", "Text analytics")
.setParameter("text", text)
.build();
HttpPost post = new HttpPost(uri);
//the following headers aren't necessary for getting a response
post.setHeader("User-Agent", "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/21.0");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
System.out.println( "executing request " + post.getRequestLine());
HttpResponse response = client.execute(post);
String xmlString = EntityUtils.toString(response.getEntity());
System.out.println(xmlString);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我有一個類似的問題,就我而言,這是一個防火牆問題。 它會關閉連接,因為它正確地發現它可疑。 嘗試關閉防火牆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.