2015-09-16 84 views
0

对于这个问题,我非常抱歉,但我是Android和Android Studio的新手。 我想发送一个请求到一个API,我想查询的结果。 我从来没有发送HTTP请求,我已经搜索在谷歌我有锯子做这样的事情:如何创建JSON的对象

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上设置了<uses-permission android:name="android.permission.INTERNET"></uses-permission>

谢谢。

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

+0

当您在主线程上执行“网络调用”时,会出现'android.os.NetworkOnMainThreadException'。您应该使用'Handler'或'AsyncTask'代替 –

回答

0

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

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

} 
+0

如何导入新的DefaultHttpClient();? –

+0

import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; – Asmi

+0

当我写上面的代码 – Asmi