【问题标题】:how to post json data to the restful API in header to get json response android如何将json数据发布到标头中的restful API以获取json响应android
【发布时间】:2016-08-28 14:07:28
【问题描述】:

我想与 api 建立连接并将字符串数据发布到 api 以获得 json 结果,但我不知道这是如何完成的,这是我的代码,谁能告诉我如何将 json 数据放入这个 url 连接和通过吧

 package practise.c.practise;

    import android.os.Handler;
    import android.os.Message;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Base64;
    import android.util.Log;
    import android.widget.Toast;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;

    public class API extends AppCompatActivity {
        String USERID;
        String APIKEY;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_api);
            Log.d("oncreate", "onCreate: ");

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        Log.d("threadrun", "onCreate: ");
                        URL url = new URL("https://api.api.com/v1");
                        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                        String userCredentials = "2223:6c005hhhh1eggggf4447b59bfed";
                        String basicAuth = Base64.encodeToString(userCredentials.getBytes(),Base64.DEFAULT);
                        httpURLConnection.setRequestProperty ("Authorization","Basic" + basicAuth);
                        httpURLConnection.setRequestMethod("POST");
                        httpURLConnection.setRequestProperty("Accept-Language", "en");
                        int responseCode = httpURLConnection.getResponseCode();

                        Log.d("responsecode", "run: "+responseCode);

                        if(responseCode == 200){

                            InputStream inputStr = httpURLConnection.getInputStream();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStr));
                            StringBuilder result = new StringBuilder();
                            String line;
                            while((line = reader.readLine()) != null) {
                                result.append(line);
                            }
                            Log.d("API:DATA", "run: "+result);

                        }



                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
            thread.start();





        }




    }

【问题讨论】:

    标签: android json


    【解决方案1】:

    试试下面的代码模板。您需要的内容在代码中的 cmets 中进行了说明。

    /**
     * Created by sibidharan on 18/11/14.
     * Sample class
     */
    
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.os.Build;
    import android.util.Log;
    
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.content.ByteArrayBody;
    import org.apache.http.entity.mime.content.ContentBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.ByteArrayOutputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.SocketTimeoutException;
    import java.net.URL;
    import java.net.UnknownHostException;
    
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLPeerUnverifiedException;
    
    /*
    Usage of the class
    
    Create all the necessary API Call methods you need.
    And either use a Thread or AsyncTask to call the following.
    
        JSONObject response = ApiUrlCalls.login("username", "passowrd");
    
    After the response is obtained, check for status code like
    
        if(response.getInt("status_code") == 200){
            //TODO: code something
        } else {
            //TODO: code something
        }
    */
    
    public class ApiUrlCalls {
    
        private String HOST = "https://domain/path/"; //This will be concated with the function needed. Ref:1
    
        /*
            Now utilizing the method is so simple. Lets consider a login function, which sends username and password.
            See below for example.
        */
    
        public static JSONObject login(String username, String password){
    
            String functionCall = "login";
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("username", username)
                    .appendQueryParameter("password", password);
    
            /*
                The return calls the apiPost method for processing.
                Make sure this should't happen in the UI thread, orelse, NetworkOnMainThread exception will be thrown.
            */
            return apiPost(builder, functionCall);
    
        }
    
        /*
            This method is the one which performs POST operation. If you need GET, just change it
            in like Connection.setRequestMethod("GET")
        */
        private static JSONObject apiPost(Uri.Builder builder, String function){
            try {
                int TIMEOUT = 15000;
                JSONObject jsonObject = new JSONObject();
                try {
                    URL url = null;
                    String response = "";
    
                    /*
                        Ref:1
                        As mentioned, here below, in case the function is "login",
                        url looks like https://domain/path/login
    
                        This is generally a rewrited form by .htaccess in server.
                        If you need knowledge on RESTful API in PHP, refer 
                        http://stackoverflow.com/questions/34997738/creating-restful-api-what-kind-of-headers-should-be-put-out-before-the-response/35000332#35000332
    
                        I have answered how to create a RESTful API. It matches the above URL format, it also includes the .htaccess
                    */
    
                    url = new URL(HOST + function);
    
                    HttpsURLConnection conn = null;
                    conn = (HttpsURLConnection) url.openConnection();
                    assert conn != null;
                    conn.setReadTimeout(TIMEOUT);
                    conn.setConnectTimeout(TIMEOUT);
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
    
                    String query = builder.build().getEncodedQuery();
    
                    OutputStream os = conn.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    writer.write(query);
                    writer.flush();
                    writer.close();
                    os.close();
                    conn.connect();
    
    
                    int responseCode = conn.getResponseCode();
                    String responseMessage = conn.getResponseMessage();
                    jsonObject.put("status_code", responseCode);
                    jsonObject.put("status_message", responseMessage);
    
                    /*The if condition below will check if status code is greater than 400 and sets error status
                    even before trying to read content, because HttpUrlConnection classes will throw exceptions
                    for status codes 4xx and 5xx. You cannot read content for status codes 4xx and 5xx in HttpUrlConnection
                    classes. 
                    */
    
                    if (jsonObject.getInt("status_code") >= 400) {
                        jsonObject.put("status", "Error");
                        jsonObject.put("msg", "Something is not good. Try again later.");
                        return jsonObject;
                    }
    
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
                    while ((line = br.readLine()) != null) {
                        response += line;
                    }
                    //Log.d("RESP", response);
    
                    /*
                        After the actual payload is read as a string, it is time to change it into JSON.
                        Simply when it starts with "[" it should be a JSON array and when it starts with "{"
                        it is a JSONObject. That is what hapenning below.
                    */
                    if(response.startsWith("[")) {
                        jsonObject.put("content", new JSONArray(response));
                    }
                    if(response.startsWith("{")){
                        jsonObject.put("content", new JSONObject(response));
                    }
    
    
                } catch(UnknownHostException e) {
                //No explanation needed :)
                    jsonObject.put("status", "UnknownHostException");
                    jsonObject.put("msg", "Check your internet connection");
                } catch (SocketTimeoutException){
                //This is when the connection timeouts. Timeouts can be modified by TIMEOUT variable above.
                    jsonObject.put("status", "Timeout");
                    jsonObject.put("msg", "Check your internet connection");
                } catch (SSLPeerUnverifiedException se) {
                //When an untrusted SSL Certificate is received, this happens. (Only for https.)
                    jsonObject.put("status", "SSLException");
                    jsonObject.put("msg", "Unable to establish secure connection.");
                    se.printStackTrace();
                } catch (IOException e) {
                //This generally happens when there is a trouble in connection
                    jsonObject.put("status", "IOException");
                    jsonObject.put("msg", "Check your internet connection");
                    e.printStackTrace();
                } catch(FileNotFoundException e){ 
                //There is no chance that this catch block will execute as we already checked for 4xx errors
                    jsonObject.put("status", "FileNotFoundException");
                    jsonObject.put("msg", "Some 4xx Error");
                    e.printStackTrace();
                } catch (JSONException e){ 
                //This happens when there is a troble reading the content, or some notice or warnings in content, 
                //which generally happens while we modify the server side files. Read the "msg", and it is clear now :)
                    jsonObject.put("status", "JSONException");
                    jsonObject.put("msg", "We are experiencing a glitch, try back in sometime.");
                    e.printStackTrace();
                } return jsonObject;
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    
    }
    

    【讨论】:

    • 你能告诉我我应该在我的代码中做什么以及我应该如何在我的代码中传递数据吗?你的解决方案很好但是......我将不得不改变我的代码的逻辑......是我的代码错了吗?
    • 你的代码看起来不错,但是API层是从AppCompactActivity扩展而来的,不推荐。只需像我在上面的代码中解释的那样创建一个方法,其余的将自动完成,因为我在那里编写了函数。就像示例登录功能一样,只需让我的方法知道它必须发布什么。从静态方法调用 apiPost 方法。简单的。阅读代码两次以获得想法。
    • Uri.Builder 保存要发布的表单数据 [POST/GET]。添加尽可能多的内容,然后使用function 字符串将其发送到apiPost() 方法,http://example.com/api/function 或它必须是这样。它将附加到主机,并进一步处理,并为您提供结果 JSON。就像吃蛋糕一样简单。
    • 嘿,我已经对我的代码进行了更改......在你的代码的帮助下,但我收到了错误代码 500,你能告诉我问题是什么吗?让我给你看我的代码
    • D/responseerror: run: buffer(com.android.okhttp.internal.http.HttpConnection$FixedLengthSource@21df95d).inputStream() 05-04 13:43:43.297 1641-1658/practice。 c.practice D/responsecode: run: 500 this is my logcat error
    【解决方案2】:

    我刚刚对我的两行代码进行了更改,我的代码开始工作了

    URL url = new URL("http://api.api.com/v1");// http 而不是 https httpURLConnection.setRequestProperty("Authorization","Basic" + basicAuth);//Basic后面给空间

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 2019-11-06
      相关资源
      最近更新 更多