示例代码(请注意,HTTP header中的user token前面,需要加"TOKEN "(此处有一个空格)作为前缀):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public final class HTTPToolKit {
private static Log log = LogFactory.getLog(HTTPToolKit.class);
public static String doGet(String url, String queryString, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
try {
if (StringUtils.isNotBlank(queryString))
method.setQueryString(URIUtil.encodeQuery(queryString));
method.setRequestHeader("Authorization", "TOKEN AgAAAAbh*******************SExcVqgqa");
method.setRequestHeader("X-EBAY-GLOBAL-ID", "EBAY-US");
method.setRequestHeader("Accept", "application/xml");
client.executeMethod(method);
System.out.println(method.getStatusCode() + method.getResponseBodyAsString());
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (URIException e) {
log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
} catch (IOException e) {
log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response.toString();
}
public static void main(String[] args) {
String y = doGet("https://svcs.ebay.com/services/selling/listingrecommendation/v1/item/recommendationItemIds?recommendationType=Picture&pageNumber=1&entriesPerPage=10", null, "UTF-8", true);
System.out.println(y);
}
}