2013-08-20 109 views
-1

我在java中編寫了下面的代碼,通過POST變量將一些數據發送到我的網站的PHP文件,然後我想獲得本網站的源代碼。帶有POST數據的Java HTTP請求

public DatabaseRequest(String url, IDatabaseCallback db_cb) 
     { 
      this.db_cb = db_cb; 
      site_url = url; 
      client = new DefaultHttpClient(); 
      request = new HttpPost(site_url); 
      responseHandler = new BasicResponseHandler(); 
      nameValuePairs = new ArrayList<NameValuePair>(0); 
     } 

     public void addParameter(List<NameValuePair> newNameValuePairs) 
     { 
      nameValuePairs = newNameValuePairs; 
     } 

     public void run() 
     { 
      db_cb.databaseFinish(getContent()); 
     } 

     public String[] getContent() 
     { 

      String result = ""; 
      try { 
       request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       result = client.execute(request, responseHandler); 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      String[] result_arr = result.trim().split("<br>"); 
      for (int i = 0; i < result_arr.length; i++) 
      { 
       result_arr[i] = result_arr[i].trim(); 
      } 
      return result_arr; 
     } 

當我要運行該代碼,然後日食引發以下錯誤消息: Error Message

+0

你如何運行此代碼? – Phil

回答

1

試試這個:

// executes the request and gets the response. 
HttpResponse response = client.execute(httpPostRequest); 
// get the status code--- 200 = Http.OK 
int statusCode = response.getStatusLine().getStatusCode(); 

HttpEntity httpEntity = response.getEntity(); 
responseBody = httpEntity.getContent();  

if (statusCode = 200) { 
    // process the responseBody. 
} 
else{ 
    // there is some error in responsebody 
} 

編輯:要處理UnsupportedEncodingException

在發出HTTP請求之前,您需要將發佈數據編碼爲c將所有字符串數據轉換爲有效的url格式。

// Url Encoding the POST parameters 
try { 
    httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
} 
catch (UnsupportedEncodingException e) { 
    // writing error to Log 
    e.printStackTrace(); 
} 
+0

對於responseBody,你可以使用String responseBody = EntityUtils.toString(response.getEntity()); –

+0

這會引發不支持的編碼錯誤(uft-8)。我必須爲我的PHP文件設置不同的編碼類型嗎? –

+0

你能不能粘貼logcat? –