How to send a JSON object over Request with Android?

前端 未结 8 1854
慢半拍i
慢半拍i 2020-11-22 03:32

I want to send the following JSON text

{\"Email\":\"aaa@tbbb.com\",\"Password\":\"123456\"}

to a web service and read the response. I kno

相关标签:
8条回答
  • 2020-11-22 03:47

    Now since the HttpClient is deprecated the current working code is to use the HttpUrlConnection to create the connection and write the and read from the connection. But I preferred to use the Volley. This library is from android AOSP. I found very easy to use to make JsonObjectRequest or JsonArrayRequest

    0 讨论(0)
  • 2020-11-22 03:49

    HttpPost is deprecated by Android Api Level 22. So, Use HttpUrlConnection for further.

    public static String makeRequest(String uri, String json) {
        HttpURLConnection urlConnection;
        String url;
        String data = json;
        String result = null;
        try {
            //Connect 
            urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();
    
            //Write
            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();
    
            //Read
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
    
            String line = null;
            StringBuilder sb = new StringBuilder();
    
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
    
            bufferedReader.close();
            result = sb.toString();
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-11-22 03:49
    public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
        JSONArray array;
        @Override
        protected JSONArray doInBackground(Void... params) {
    
            try {
                commonurl cu = new commonurl();
                String u = cu.geturl("tempshowusermain.php");
                URL url =new URL(u);
              //  URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Content-Type", "application/json");
                httpURLConnection.setRequestProperty("Accept", "application/json");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                httpURLConnection.setDoInput(true);
                httpURLConnection.connect();
    
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("lid",lid);
    
    
                DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
                outputStream.write(jsonObject.toString().getBytes("UTF-8"));
    
                int code = httpURLConnection.getResponseCode();
                if (code == 200) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
    
                    StringBuffer stringBuffer = new StringBuffer();
                    String line;
    
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuffer.append(line);
                    }
                    object =  new JSONObject(stringBuffer.toString());
                 //   array = new JSONArray(stringBuffer.toString());
                    array = object.getJSONArray("response");
    
                }
    
            } catch (Exception e) {
    
                e.printStackTrace();
            }
            return array;
    
    
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    
    
    
        }
    
        @Override
        protected void onPostExecute(JSONArray array) {
            super.onPostExecute(array);
            try {
                for (int x = 0; x < array.length(); x++) {
    
                    object = array.getJSONObject(x);
                    ComonUserView commUserView=new ComonUserView();//  commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
                    //pidArray.add(jsonObject2.getString("pid").toString());
    
                    commUserView.setLid(object.get("lid").toString());
                    commUserView.setUname(object.get("uname").toString());
                    commUserView.setAboutme(object.get("aboutme").toString());
                    commUserView.setHeight(object.get("height").toString());
                    commUserView.setAge(object.get("age").toString());
                    commUserView.setWeight(object.get("weight").toString());
                    commUserView.setBodytype(object.get("bodytype").toString());
                    commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
                    commUserView.setImagepath(object.get("imagepath").toString());
                    commUserView.setDistance(object.get("distance").toString());
                    commUserView.setLookingfor(object.get("lookingfor").toString());
                    commUserView.setStatus(object.get("status").toString());
    
                    cm.add(commUserView);
                }
                custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
              gridusername.setAdapter(custuserprof);
                //  listusername.setAdapter(custuserprof);
                } catch (Exception e) {
    
                    e.printStackTrace();
            }
        }
    
    0 讨论(0)
  • 2020-11-22 03:53

    Nothing could be simple than this. Use OkHttpLibrary

    Create your json

    JSONObject requestObject = new JSONObject();
    requestObject.put("Email", email);
    requestObject.put("Password", password);
    

    and send it like this.

    OkHttpClient client = new OkHttpClient();
    
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
                .addHeader("Content-Type","application/json")
                .url(url)
                .post(requestObject.toString())
                .build();
    
    okhttp3.Response response = client.newCall(request).execute();
    
    0 讨论(0)
  • 2020-11-22 03:54

    Android doesn't have special code for sending and receiving HTTP, you can use standard Java code. I'd recommend using the Apache HTTP client, which comes with Android. Here's a snippet of code I used to send an HTTP POST.

    I don't understand what sending the object in a variable named "jason" has to do with anything. If you're not sure what exactly the server wants, consider writing a test program to send various strings to the server until you know what format it needs to be in.

    int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
    String postMessage="{}"; //HERE_YOUR_POST_STRING.
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpClient client = new DefaultHttpClient(httpParams);
    
    HttpPost request = new HttpPost(serverUrl);
    request.setEntity(new ByteArrayEntity(
        postMessage.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(request);
    
    0 讨论(0)
  • 2020-11-22 03:54
    public void postData(String url,JSONObject obj) {
        // Create a new HttpClient and Post Header
    
        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 10000);
        HttpClient httpclient = new DefaultHttpClient(myParams );
        String json=obj.toString();
    
        try {
    
            HttpPost httppost = new HttpPost(url.toString());
            httppost.setHeader("Content-type", "application/json");
    
            StringEntity se = new StringEntity(obj.toString()); 
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httppost.setEntity(se); 
    
            HttpResponse response = httpclient.execute(httppost);
            String temp = EntityUtils.toString(response.getEntity());
            Log.i("tag", temp);
    
    
        } catch (ClientProtocolException e) {
    
        } catch (IOException e) {
        }
    }
    
    0 讨论(0)
提交回复
热议问题