通过webservice获取404、403错误时如何获取得到的Json Response?

Posted

技术标签:

【中文标题】通过webservice获取404、403错误时如何获取得到的Json Response?【英文标题】:How to get the Json Response obtained when getting 404, 403 errors through webservice? 【发布时间】:2018-03-13 12:03:16 【问题描述】:

当我调用 Web 服务时,它会响应 403 和一些类似这样的响应数据。


  "code": "[jwt_auth] invalid_email",
  "message": "Dummy MEssage",
  "data": 
    "status": 403
  

我的代码如下所示

final AsyncTask<Void, String, String> waitForCompletion = new AsyncTask<Void, String, String>() 
            ProgressDialog progressDialog;
            @Override
            protected void onPreExecute()  
               super.onPreExecute();
               //Show Progress
            

            @Override
            public synchronized String doInBackground(Void... params) 
                String res = "";
                String charset = "UTF-8";
                String requestURL = "www.myurl.com";

                try 

                    MultipartUtility multipart = new MultipartUtility(requestURL, charset);

                    multipart.addFormField("username", email);
                    multipart.addFormField("password", password);

                    List<String> response = multipart.finish();
                    for (String line : response) 
                        System.out.println(line);
                        res = line;
                        Log.d("Message" , "Obtained" + response);
                    
                 catch (IOException ex) 
                    System.err.println(ex);
                    dismissProgressDialog(progressDialog);
                
                return res;

            

            @Override
            protected void onPostExecute(String result) 
                dismissProgressDialog(progressDialog);
                if (hasValue(result)) 
                    UserLogin response = (new Gson()).fromJson(result, new TypeToken<UserLogin>() 
                    .getType());

                    if (result.contains("message")) 
                        // Show error message
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) 
                            showMessageAlert(html.fromHtml(response.getMessage(), Html.FROM_HTML_MODE_COMPACT), getString(R.string.app_name), LoginActivity.this);
                         else 
                            showMessageAlert(Html.fromHtml(response.getMessage()), getString(R.string.app_name), LoginActivity.this);
                        
                     else 
                        setUserId(LoginActivity.this , String.valueOf(response.getUserId()));
                        setToken(LoginActivity.this, response.getToken());
                        setLoginInformation(LoginActivity.this, result);
                        Intent intent = new Intent(LoginActivity.this, PickSportsActivity.class);
                        startActivity(intent);
                        finish();
                    
                
            
        ;

问题是当我收到 403 和 404 错误作为响应时,如何获得响应。即使出现这些错误,我如何才能获取得到的响应。

这是我的多部分代码

public class MultipartUtility 
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;
    StringBuilder result;

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException 
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.addRequestProperty("TOKEN", "Zml0c29vOmZpdHNvb0Aj");
//        httpConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
       // httpConn.addRequestProperty("content-type", "application/x-www-form-urlencoded");httpConn.setRequestProperty("content-type", "application/x-www-form-urlencoded;  charset=utf-8");
    /*    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");*/
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    

    /**
     * Adds a form field to the request
     * @param name field name
     * @param value field value
     */
    public void addFormField(String name, String value) 
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();


         result = new StringBuilder();
        boolean first = true;
        if (first)
            first = false;
        else
            result.append("&");


        try 
            result.append(URLEncoder.encode(name, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value, "UTF-8"));
         catch (UnsupportedEncodingException e) 
            e.printStackTrace();
        
    

    /**
     * Adds a upload file section to the request
     * @param fieldName name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException 
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) 
            outputStream.write(buffer, 0, bytesRead);
        
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();

        try 
            result.append(URLEncoder.encode(fieldName, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(fileName, "UTF-8"));
         catch (UnsupportedEncodingException e) 
            e.printStackTrace();
        

    

    /**
     * Adds a header field to the request.
     * @param name - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) 
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    

    /**
     * Completes the request and receives response from the server.
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public List<String> finish() throws IOException 
        List<String> response = new ArrayList<String>();

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) 
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) 
                response.add(line);
            
            reader.close();
            httpConn.disconnect();
        
        else if(status==500)

            throw new IOException("Server HTTP_INTERNAL_ERROR : " + status);
        else 

            throw new IOException("Server returned non-OK status: " + status);
        

        return response;
    

【问题讨论】:

也发布你的 multipartutility 类。 嗨,我已经添加了我的 Multipart 代码 【参考方案1】:

在您的完成方法代码中查看 int 变量 status

此状态变量将为您提供从服务器返回的响应代码。

代码中的if 条件检查响应代码200 和500。您可以为此添加自己的逻辑。

您还可以通过使用 StringBuilder 而不是使用 arraylist 作为响应来简化您的完成方法代码。

【讨论】:

这是您正在使用的 MultipartUtility 类中的 finish() 方法public String finish() ... 不,它不是 List&lt;String&gt; response = multipart.finish(); 好的,但是当我收到错误代码 403 时,我仍然不知道如何获得这些响应 您在 http_ok​​ 中添加的代码 if case 将与您的其他情况相同。如果您的成功和失败响应具有不同的 json 结构,那么您必须相应地解析它们。

以上是关于通过webservice获取404、403错误时如何获取得到的Json Response?的主要内容,如果未能解决你的问题,请参考以下文章

十月CMS 401、402、403、503、400错误代码处理

遇到IIS7配置PHP出现403和404错误的解决办法

Amazon S3 - 尽管有 GetObject 限制,但返回 403 错误而不是 404

Django 自定义错误页面 403 404...

Django 自定义错误页面 403 404...

当我使用谷歌你管 API 获取搜索结果时,它给出 403 错误