-1

I need to send a JSON string to a url using POST. the string should be:

data={"cmd":"sign_in",....}

So in doInBackground, I used this code:

HttpURLConnection connection = null;

DataOutputStream outputStream = null;

String json = "{\"cmd\": \"sign_in\",...";

try{

URL url = new URL("https://...?data=");

connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(json);
osw.flush();
osw.close();    
}

I check my response using

int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseMessage.length()>0)
return true;

But I am not receiving any response. The response string should be a JSON string. But I used length() to see whether any string is being returned. Should this code work? Any help?

musica
  • 1,373
  • 3
  • 15
  • 34
Amit
  • 121
  • 1
  • 3
  • 12

2 Answers2

0

You can use FormEncodingBuilder like this

OkHttpClient client = TCY.getmInstance().getOkHttpClient();
        client.setConnectTimeout(120, TimeUnit.SECONDS); // connect timeout
        client.setReadTimeout(120, TimeUnit.SECONDS); // socket timeout
        //  System.setProperty("http.keepAlive", "true");
        formBody.add("abc", abc);
        formBody.add("username", username);
        formBody.add("password", "password");

        RequestBody body = formBody.build();
        Request request = new Request.Builder()
                .url(url)
                .cacheControl(new CacheControl.Builder()
                        .maxStale(1, TimeUnit.DAYS)
                        .build())
                .post(body)
               /* .header("Connection", " keep-alive")*/
                .build();
        hit_link = "url= " + url + " params= " + bodyToString(request);

        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                result = response.toString();
                if (result.equals("") || result.equals("null") || result.length() == 0) {
                    // CommonUtilities.showToast(context, "Something went wrong. Try later.");
                }
            } else {

            }
            result = response.body().string();
           /* Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                Log.e("CallAddr", responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }*/
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
0

Try this

        URL obj = new URL(this.url);//url assigned on constructor
        HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setConnectTimeout(5000);
        String urlParameters = this.headerData.toString();//headerdata is json and conveting is to string to send to server.


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


        int responseCode = httpURLConnection.getResponseCode();//getting response code

        BufferedReader bufferedReader = null;
        if (responseCode == 200) {
            bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        } else {
            bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
        }
Developer
  • 183
  • 8