在android中用post方法发送数据

时间:2017-01-07 10:50:31

标签: android json post

这是我正在使用的代码:

                HttpClient client = new DefaultHttpClient();
                HttpPost method = new  HttpPost("http://192.168.1.1/value/_0/_0");
                JSONObject object = new JSONObject();
                try {
                    object.put("Val", "0");
                    msg = object.toString();
                    method.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("admin", "00000000"), "UTF-8", false));
                    method.setHeader("Content-Type", "application/json");
                    method.setEntity(new StringEntity(msg, "UTF8"));
                    client.execute(method);
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }

这里我添加标头用于身份验证和内容类型的请求。这有什么不对,我不知道。

2 个答案:

答案 0 :(得分:0)

这样做:

   public static String postJson(String sUrl, String jsonParams){
   String response = "";
   try {
      HttpURLConnection conn;
      //just encoding space from url
      URL url = new URL(sUrl.replace(" ", "%20"));
      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("content-type", "application/json");

      byte[] outputInBytes = jsonParams.getBytes("UTF-8");
      OutputStream os = conn.getOutputStream();
      os.write(outputInBytes);
      os.close();
      conn.connect();

      if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
         InputStream inputStream = conn.getInputStream();
         response = convertStreamToString(inputStream);
      }

      Log.e("Request: ", sUrl+jsonParams+"");
      Log.e("Response: ", response+"");
   } catch (IOException e) {
      e.printStackTrace();
   }
   return response;
}

public static String convertStreamToString(InputStream inputStream) {
   if (inputStream == null)
      return null;
   StringBuilder sb = new StringBuilder();
   try {
      BufferedReader r = new BufferedReader(new InputStreamReader(inputStream), 1024);
      String line;
      while ((line = r.readLine()) != null) {
         sb.append(line);
      }
   } catch (Exception e) {
      e.printStackTrace();
   }
   return sb.toString();
}

答案 1 :(得分:0)

您需要使用UrlConnection,现在不推荐使用DefaultHttpClient()。

public String  performPostCall(String requestURL,
    HashMap<String, String> postDataParams) {

URL url;
String response = "";
try {
    url = new URL(requestURL);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(15000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);


    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getPostDataString(postDataParams));

    writer.flush();
    writer.close();
    os.close();
    int responseCode=conn.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line=br.readLine()) != null) {
            response+=line;
        }
    }
    else {
        response="";    

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

return response;

}