java - 在 Android 中向 urlConnection 添加标头
问题描述
我正在尝试通过 url api 解析 android 中的 XML 文件。
虽然我不断收到以下错误:
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
(HTTPLog)-Static: isSBSettingEnabled false
W/System.err: java.io.FileNotFoundException:
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:26)
at com.example.finalyearapp.Carbonfootprint.HandleXml$1.run(HandleXml.java:102)
at java.lang.Thread.run(Thread.java:764)
我相信找不到该文件,因为我没有正确添加标题目前我以这种方式调用链接:
我的字符串网址:
String url = "https://apis.berkeley.edu/coolclimate/footprint input_size=" + population +
"&input_footprint_transportation_fuel1=1"+
"&input_footprint_transportation_miles1="+miles+
"&input_footprint_transportation_mpg1="+ mpg +
"&input_footprint_transportation_bus="+ bushours +
"&input_footprint_transportation_commuter=" + trainhours +
"&input_footprint_shopping_goods_default_furnitureappliances=" + household +
"&input_footprint_shopping_goods_default_clothing=" + clothes +
"&input_footprint_shopping_goods_default_other_personalcare=" + beauty +
"&input_footprint_shopping_goods_default_other_entertainment=" + entertainment +
"&input_footprint_housing_electricity_dollars="+yearlyvalue+
"&input_footprint_housing_naturalgas_dollars="+ yearlyvalue +
" -H \"accept: application/json\" -H \"app_id: #\" -H \"app_key: #";
你可以看到我有标题的 url 的结尾。
我怎么称呼它:
public void fetchXML(){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(urlstring);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setReadTimeout(100000);
connect.setConnectTimeout(150000);
connect.setRequestMethod("GET");
connect.setDoInput(true);
connect.connect();
InputStream stream = connect.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}catch (Exception e){
e.printStackTrace();
}
}
});
解决方案
您可以通过在 HttpURLConnection 上调用 setRequestProperty 来添加标头。
connect.setRequestProperty("Content-Type", "application/json");
在尝试解析回复之前,您可能应该检查响应代码并继续使用 http 200。
在此处提问时,您还应注意不要共享 API 密钥等私有数据。
推荐阅读
- javascript - 使用两个数组将对象分组到新数组中
- python - Python 2 和 3 之间 threading.Event().wait 的大时间差
- asp.net-mvc - 使用 web.config 排除 MVC 角色提供程序的目录
- python - 在 python 3.x 中更改图像文件的 md5 签名
- javascript - 改变视口/屏幕宽度js
- javascript - 如何制作一个将背景变成渐变的按钮?
- javascript - 用 promises 和 undefined var 理解奇怪的错误
- python - 在 matplotlib 图的中间水平居中 y 标签
- javascript - 如何跨突变将新附加值添加到状态?
- python-3.x - 从python中的列表中删除子列表