【问题标题】:how to create a JSON's object [duplicate]如何创建 JSON 对象 [重复]
【发布时间】:2015-09-16 07:22:44
【问题描述】:

对于这个问题我很抱歉,但我是 Android 和 Android Studio 的新手。 我想向 api 发送一个请求,我想要查询的结果。 我从来没有发送过 HTTP 请求,我在 google 上搜索过我看到过这样的事情:

public class HttpClient {
private static final String TAG = "HttpClient";

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString= convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

            return jsonObjRecv;
        } 

    }
    catch (Exception e)
    {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}


private 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.
     * 
     * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
     */
    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();
}

}

在我的其他活动中,我设置了私有静态最终字符串 URL = myurl; (这是一个例子)。 我认为这是正确的方法,但我真的不确定我在做什么......另一个问题是当我尝试执行HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); 我有这个错误:Android - android.os.NetworkOnMainThreadException 我认为问题是我不知道如何导入

org.apache.http.Header;
import org.apache.http.HttpEntity;

等等。 如何将它们导入我的项目?我已经在我的 AndroidManifest 上设置了&lt;uses-permission android:name="android.permission.INTERNET"&gt;&lt;/uses-permission&gt;

谢谢。

编辑(已解决): 在 23.0.0 Gradle 版本上,apache 包不起作用,因为它已被弃用,如果我尝试降级我的 Grandle 版本,我的布局等有问题。我找到的解决方案是使用 Volley jar 和方法。

【问题讨论】:

  • android.os.NetworkOnMainThreadException 在主线程上执行 Network Call 时发生。您应该改用HandlerAsyncTask

标签: android json apache http android-studio


【解决方案1】:

此代码在我的项目中正常工作,可将 json 数据发送到服务器并接受响应。

public static final String url ="your url";

after this all your code here i.e json or something 

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("allData",jarray.toString()));
    String resultServer  = getHttpPost(url,params); // Here to pass the url and parameter as student data

// getHttpPost method

    private String getHttpPost(String url, List<NameValuePair> params) 
    {

        // TODO Auto-generated method stub

             sb = new StringBuilder();
             HttpClient client = new DefaultHttpClient();
             HttpPost httpPost = new HttpPost(url);
            //  Log.d("Entire httppost::", " " + httpPost);
             //httpPost.setHeader("Accept", "application/json");
              //  httpPost.setHeader("Content-type", "application/json");
             try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                    HttpResponse response = client.execute(httpPost); // get the response from same url
                    HttpEntity entity = response.getEntity();         // set the response into HttpEntity Object
                    is = entity.getContent();                         // Assign the response content to inputStream Object 
                    Log.e("server Response", "json format "+is);


                } catch (ClientProtocolException e) 
                    {
                    e.printStackTrace();
                    } 
                 catch (IOException e) 
                     {
                     e.printStackTrace();
                     }

             if(is!=null )
             {
             try{   //this try block is for to handlethe response inputstream
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    sb = new StringBuilder();
                    sb.append(reader.readLine() + "\n");
                    String line="0";

                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }

                    is.close();
                    result=sb.toString();
                    Log.d("RESULT inside try block(sb) ", " " + result);
                }catch(Exception e){
                    Log.e("log_tag", "Error converting result "+e.toString());
                }

return sb.toString();
         }  

}

【讨论】:

  • 如何导入新的 DefaultHttpClient();?
  • 导入 org.apache.http.HttpEntity;导入 org.apache.http.HttpResponse;导入 org.apache.http.NameValuePair;导入 org.apache.http.StatusLine;导入 org.apache.http.client.ClientProtocolException;导入 org.apache.http.client.HttpClient;导入 org.apache.http.client.entity.UrlEncodedFormEntity;导入 org.apache.http.client.methods.HttpGet;导入 org.apache.http.client.methods.HttpPost;导入 org.apache.http.impl.client.DefaultHttpClient;导入 org.apache.http.message.BasicNameValuePair;导入 org.json.JSONArray;导入 org.json.JSONException;导入 org.json.JSONObject;
  • 当我编写上述代码时,所有导入都是自动导入
  • 而且它工作正常..
  • 无法解析符号“HttpEntity”,你有导入 jar 依赖或类似的东西吗? ——
猜你喜欢
  • 1970-01-01
  • 2014-04-28
  • 2017-11-30
  • 2013-12-21
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
相关资源
最近更新 更多