使用POST使用HttpURLConnection发送json数据

时间:2016-09-22 05:14:42

标签: android json httpurlconnection

我需要使用JSONurl发送POST字符串。 字符串应该是:

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

所以在doInBackground中,我使用了这段代码:

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();    
}

我使用

检查我的回复
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseMessage.length()>0)
return true;

但我没有收到任何回复。响应字符串应为JSON字符串。但我使用length()来查看是否返回了任何字符串。 该代码应该有效吗?有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

您可以像这样使用FormEncodingBuilder

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;

答案 1 :(得分:0)

试试这个

        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()));
        }