【问题标题】:Sending JSON params with HTTPS request使用 HTTPS 请求发送 JSON 参数
【发布时间】:2013-09-14 06:45:15
【问题描述】:

我需要调用“HTTPS”api并将JSON参数传递给服务器。
现在我正在尝试这样:

HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost("https://myapi call goes here...");
            httppost.setHeader("Content-Type", "application/json");

            try
            {

                JSONObject j = new JSONObject();
                j.put("email", "my email value goes here");

                StringEntity s = new StringEntity(j.toString());

                httppost.setEntity(s);
                HttpResponse response = httpclient.execute(httppost);

                /* Checking response */
                if(response != null)
                {
                    responseBody = EntityUtils.toString(response.getEntity());


                }
                if(responseBody.equals("ok"))
                {



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


            }  

但它给了我一个例外:SSL Peer unverified: No Peer Certificate.
请注意,我只能使用 HTTPS 来调用 api。

有人知道吗?

【问题讨论】:

    标签: android https


    【解决方案1】:

    看看这个answer。它得到了很好的解释,并且可能是您更正代码所需要的。

    【讨论】:

      【解决方案2】:

      使用下面的代码,它还需要在 url 中放入 json。检查代码。

      public void login(Bundle bndl) {
      
          try {
              // /////////////////////////
              final int TIMEOUT_MILLISEC = 8000;
              JSONObject json = new JSONObject();
              json.put("email", bndl.getString("email"));
              json.put("psw", bndl.getString("psw"));
              HttpParams httpParams = new BasicHttpParams();
              HttpConnectionParams.setConnectionTimeout(httpParams,
                      TIMEOUT_MILLISEC);
              HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
              HttpClient client = new DefaultHttpClient(httpParams);
      
              String url = "http://www.abc.com/login.php/?email="
                      + bndl.getString("email") + "&psw=" + bndl.getString("psw");
      
              HttpPost request = new HttpPost(url);
              request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                      "UTF8")));
              request.setHeader("json", json.toString());
              HttpResponse response = client.execute(request);
              HttpEntity entity = response.getEntity();
              // If the response does not enclose an entity, there is no need
              if (entity != null) {
                  InputStream instream = entity.getContent();
      
                  String result = RestClient.convertStreamToString(instream);
      
              }
          } catch (Exception ex) {
      
          }
      }
      

      以下是支持类,复制粘贴即可。它的名字是 RestClient

      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      
      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.client.ClientProtocolException;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.json.JSONArray;
      import org.json.JSONException;
      import org.json.JSONObject;
      
      import android.util.Log;
      public class RestClient {
      
          public static String convertStreamToString(InputStream is) {
          /*
           * To convert the InputStream to String we use the BufferedReader.readLine()
           * method. We iterate until the BufferedReader return null which means
           * there's no more data to read. Each line will appended to a StringBuilder
           * and returned as String.
           */
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
          StringBuilder sb = new StringBuilder();
      
          String line = null;
          try {
              while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
              }
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              try {
                  is.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          return sb.toString();
      }
      
      /* This is a test function which will connects to a given
       * rest service and prints it's response to Android Log with
       * labels "Praeda".
       */
      public static void connect(String url)
      {
      
          HttpClient httpclient = new DefaultHttpClient();
      
          // Prepare a request object
          HttpGet httpget = new HttpGet(url); 
      
          // Execute the request
          HttpResponse response;
          try {
              response = httpclient.execute(httpget);
              // Examine the response status
              Log.i("Praeda",response.getStatusLine().toString());
      
              // Get hold of the response entity
              HttpEntity entity = response.getEntity();
              // If the response does not enclose an entity, there is no need
              // to worry about connection release
      
              if (entity != null) {
      
                  // A Simple JSON Response Read
                  InputStream instream = entity.getContent();
                  String result= convertStreamToString(instream);
                  Log.i("Praeda",result);
      
                  // A Simple JSONObject Creation
                  JSONObject json=new JSONObject(result);
                  Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
      
                  // A Simple JSONObject Parsing
                  JSONArray nameArray=json.names();
                  JSONArray valArray=json.toJSONArray(nameArray);
                  for(int i=0;i<valArray.length();i++)
                  {
                      Log.i("Praeda","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
                              +"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
                  }
      
                  // A Simple JSONObject Value Pushing
                  json.put("sample key", "sample value");
                  Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
      
                  // Closing the input stream will trigger connection release
                  instream.close();
              }
      
      
          } catch (ClientProtocolException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
      }
      

      【讨论】:

      • 这是一个http示例。问题是如何完成一个更复杂的 https 连接。
      猜你喜欢
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 2013-09-25
      相关资源
      最近更新 更多