2015-09-16 2 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; 

и т.д .. Как импортировать их в свой проект? Я уже установил <uses-permission android:name="android.permission.INTERNET"></uses-permission> на моем AndroidManifest.

спасибо.

EDIT (RESOLVED): В версии 23.0.0 Gradle пакет apache не работает, потому что он устарел, если я пытаюсь понизить мою большую версию, у меня возникла проблема с компоновкой и т. Д. Решение, которое я есть находка - использовать банку и метод волейбола.

+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

импорт org.apache.http.HttpEntity; импорт 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; импорт org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; – Asmi

+0

Все импортирует авто импорт когда я написал код – Asmi

Смежные вопросы