Android HTTPUrlConnection SocketTimeoutException / Indefinite Hang?

时间:2016-12-24 04:07:49

标签: java android json http post

我正在为客户端开发Android应用,我正在调用他们的API来获取应用的各个部分的信息。如果我设置了超时,则会有一个调用导致SocketTimeoutException;如果不设置超时,则会无限挂起;但是,它在Web客户端(React)上工作正常,因此它不能是服务器。

代码:

package io.voluntu.voluntu;

import android.os.AsyncTask;
import android.os.Bundle;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

public class SendApproveHours extends AsyncTask<Bundle, Void, String>{
    private StringBuilder sb = new StringBuilder();
    private String result;
    private ApproveHours approveHours;

    public SendApproveHours(ApproveHours approveHours){
        this.approveHours = approveHours;
    }

    protected String doInBackground(Bundle... params){
        Bundle b = params[0];
        String jwt = b.getString("JWT");
        System.out.println(jwt);

        boolean approve = b.getBoolean("APPROVE");
        int[] id = b.getIntArray("ID");
        try {
            URL url = new URL("http://voluntu.io/api/hour/update");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(2500 /* milliseconds */); //if i don't do this, it will hang indefinitely
            httpURLConnection.setReadTimeout(1500 /* milliseconds */);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Host", "voluntu.io");
            httpURLConnection.setRequestProperty("Origin", "http://voluntu.io");
            httpURLConnection.setRequestProperty("Referer", "http://voluntu.io/hours/approve");
            httpURLConnection.setRequestProperty("Cookie", "sessionJWT=" + jwt);

            httpURLConnection.connect();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("approveOrReject", approve);
            jsonObject.put("hourIDs", Arrays.toString(id));

            System.out.println(jsonObject);

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

            int HttpResult = httpURLConnection.getResponseCode(); //hangs here
            System.out.println("HTTP RESULT: " + HttpResult);
            if(HttpResult == HttpURLConnection.HTTP_OK){
                BufferedReader in = new BufferedReader(new InputStreamReader(
                       httpURLConnection.getInputStream(), "utf-8"
                ));
                String line;
                while((line = in.readLine()) != null){
                    sb.append(line);
                }
                in.close();
            }
            System.out.println("RESPONSE: " + sb.toString());
            httpURLConnection.disconnect();
        }
        catch (MalformedURLException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        return sb.toString();
    }

    protected void onPostExecute(String result){
        approveHours.refreshHours();
    }
}

由于某种原因,它依赖于获取HTTP响应代码。我检查了标题和正文,它们与网络版本发送的内容相同,所以我不知道它为什么不起作用。此外,调用其API的其他部分工作正常,事实上,此代码主要是从我调用API的应用程序的其他部分进行复制粘贴。感谢帮助!

1 个答案:

答案 0 :(得分:0)

我修好了。您必须使用JSONArray而不是数组,或者在将数组放入JSON对象时将数据包装在引号中。