2013-03-07 52 views
1
JSON響應

我試圖發送使用此代碼獲取POST

protected void Authenticate(String mUsername, String mPassword) 
    { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://192.168.2.5:8000/mobile/"); 

     try { 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("username", mUsername)); 
      nameValuePairs.add(new BasicNameValuePair("password", mPassword)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 
      System.out.println("this is the response "+response); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      System.out.println("CPE"+e); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      System.out.println("IOE"+e); 
     } 
    } 

我得到一個HttpResponse一個要求,就是我想實現正確的方法是什麼?如果是的話,我該如何將該響應轉換爲jSON?

LOG-CAT

this is the response [email protected] 
+0

您可以使用我的代碼。這是更廣泛的。處理不同類型的異常也 – 2013-03-07 09:43:55

+0

我試着實現你的代碼ANR !!!! – onkar 2013-03-07 09:46:27

+0

您應該調用AsyncTask中的第二個代碼 – 2013-03-07 09:51:47

回答

4

String jsonString = EntityUtils.toString(response.getEntity());

這是你所需要的

+1

你必須在AsyncTask中實現Http代碼,因爲它是網絡代碼。如果您有日誌,請將其粘貼到您的問題中,並請使用新代碼更新您的問題 – Naveen 2013-03-07 09:57:19

0

在這裏,您需要做的

HttpResponse mHttpResponse = mHttpClient.execute(httppost); 
       StatusLine status = mHttpResponse.getStatusLine(); 
       int response = status.getStatusCode(); 
0

這裏是什麼從blog爲例。希望這有助於

if (response.getStatusLine().getStatusCode() != 200) { 
     throw new RuntimeException("Failed : HTTP error code : " 
      + response.getStatusLine().getStatusCode()); 
    } 

    BufferedReader br = new BufferedReader(
        new InputStreamReader((response.getEntity().getContent()))); 

    String output; 
    System.out.println("Output from Server .... \n"); 
    while ((output = br.readLine()) != null) { 
     System.out.println(output); 
    } 

    httpClient.getConnectionManager().shutdown(); 
+0

我收到錯誤代碼403 :( – onkar 2013-03-07 09:52:11

+0

這意味着您的請求不正確,您需要在服務器端看到服務器拒絕的原因請求。http://en.wikipedia.org/wiki/HTTP_403 – 2013-03-07 11:58:38

2

這將幫助你:

public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

// function get json from url 
// by making HTTP POST or GET method 
public JSONObject makeHttpRequest(String url, String method, 
     List<NameValuePair> params) throws Exception { 

    // Making HTTP request 
    try { 

     // check for request method 
     if (method == "POST") { 
      // request method is POST 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      // new 
      HttpParams httpParameters = httpPost.getParams(); 
      // Set the timeout in milliseconds until a connection is 
      // established. 
      int timeoutConnection = 10000; 
      HttpConnectionParams.setConnectionTimeout(httpParameters, 
        timeoutConnection); 
      // Set the default socket timeout (SO_TIMEOUT) 
      // in milliseconds which is the timeout for waiting for data. 
      int timeoutSocket = 10000; 
      HttpConnectionParams 
        .setSoTimeout(httpParameters, timeoutSocket); 
      // new 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } else if (method == "GET") { 
      // request method is GET 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      String paramString = URLEncodedUtils.format(params, "utf-8"); 
      url += "?" + paramString; 
      HttpGet httpGet = new HttpGet(url); 
      // new 
      HttpParams httpParameters = httpGet.getParams(); 
      // Set the timeout in milliseconds until a connection is 
      // established. 
      int timeoutConnection = 10000; 
      HttpConnectionParams.setConnectionTimeout(httpParameters, 
        timeoutConnection); 
      // Set the default socket timeout (SO_TIMEOUT) 
      // in milliseconds which is the timeout for waiting for data. 
      int timeoutSocket = 10000; 
      HttpConnectionParams 
        .setSoTimeout(httpParameters, timeoutSocket); 
      // new 
      HttpResponse httpResponse = httpClient.execute(httpGet); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 
     } 

    } catch (UnsupportedEncodingException e) { 
     throw new Exception("Unsupported encoding error."); 
    } catch (ClientProtocolException e) { 
     throw new Exception("Client protocol error."); 
    } catch (SocketTimeoutException e) { 
     throw new Exception("Sorry, socket timeout."); 
    } catch (ConnectTimeoutException e) { 
     throw new Exception("Sorry, connection timeout."); 
    } catch (IOException e) { 
     throw new Exception("I/O error(May be server down)."); 
    } 
    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     throw new Exception(e.getMessage()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     throw new Exception(e.getMessage()); 
    } 

    // return JSON String 
    return jObj; 

} 
} 

您可以使用上面的類是這樣的: 如:

public class GetName extends AsyncTask<String, String, String> { 
String imei = "abc"; 
JSONParser jsonParser = new JSONParser(); 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
} 

protected String doInBackground(String... args) { 
    String name = null; 
    String URL = "http://192.168.2.5:8000/mobile/"; 
    List<NameValuePair> params = new ArrayList<NameValuePair>(); 
    params.add(new BasicNameValuePair("username", mUsername)); 
    params.add(new BasicNameValuePair("password", mPassword)); 
    JSONObject json; 
    try { 
     json = jsonParser.makeHttpRequest(URL, "POST", params); 
     try { 
      int success = json.getInt(Settings.SUCCESS); 
      if (success == 1) { 
       name = json.getString("name"); 
      } else { 
       name = null; 
      } 
     } catch (JSONException e) { 
      name = null; 
     } 
    } catch (Exception e1) { 
    } 
    return name; 
} 

protected void onPostExecute(String name) { 
    Toast.makeText(mcontext, name, Toast.LENGTH_SHORT).show(); 
} 
} 


如何使用它:
通過複製類代碼來創建新的JSONParse類。 然後你可以在你的應用程序中的任何地方調用它,如第二個代碼所示。