我有一个运行woocommerce的网站,我尝试通过http get请求检索产品。 当我在邮递员或我的网络浏览器上尝试网址时,一切正常。但是,在我的Android应用程序上,我没有得到任何结果。
有人没有错吗?
这是我的代码:
JSONObject json = jsonParser.httpRequest(url,"GET",params);
public JSONObject httpRequest(String url, String method, ArrayList<Pair<String,String>> params) throws SocketTimeoutException{
String response = "";
try {
URL url_o = new URL(url);
this.connection = (HttpURLConnection) url_o.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(5000);
Uri.Builder builder = new Uri.Builder();
for (int i = 0; i < params.size(); i++) {
builder.appendQueryParameter(params.get(i).first, params.get(i).second);
}
String query = builder.build().getEncodedQuery();
if(query!=null){
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
bufferedWriter.write(query);
bufferedWriter.flush();
bufferedWriter.close();
}
connection.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
if(e.getMessage().equals("connect timed out"))
throw new SocketTimeoutException();
else
e.printStackTrace();
}
try{
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while((line = bufferedReader.readLine())!=null){
stringBuilder.append(line+"\n");
}
bufferedReader.close();
response = stringBuilder.toString();
connection.disconnect();
}
}
catch(IOException e){
e.printStackTrace();
}
try{
json = new JSONObject(response);
}
catch(JSONException e){
e.printStackTrace();
}
return json;
}
知道网址是由邮递员用消费者密钥和秘密以及其他参数构建的。
httpRequest正常工作,因为我多次使用它来获取php脚本结果。
在httRequest函数结束时,var响应为空。
感谢您的帮助。
答案 0 :(得分:0)
从GET请求中删除doOutput,这些请求用于POST