如何将json数据发布到头文件中的restful API以获取json响应android

时间:2016-05-03 13:31:41

标签: android json

我想连接到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();





        }




    }

2 个答案:

答案 0 :(得分:1)

尝试以下代码模板。您需要的内容在代码中的注释中进行了解释。

/**
 * 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;
    }

}

答案 1 :(得分:0)

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

网址url =新网址(“http://api.api.com/v1”); // http而不是https httpURLConnection.setRequestProperty(“授权”,“基本”+ basicAuth); //在Basic之后给出空格