2011-10-24 380 views
2

我有我試圖在Android應用程序來模擬JavaScript代碼:Android的POST請求

下面是javascript代碼:

text = '{"username":"Hello","password":"World"}'; 
x.open("POST", url); 
x.setRequestHeader("Content-type", "application/json"); 
x.setRequestHeader("Content-length", text.length); 
x.send(text); 

這裏是我到目前爲止的Android應用程序(不工作):

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url);     
httppost.setHeader("Content-type", "application/json"); 
String text = "\"{\"username\":\"Hello\",\"password\":\"World\"}\""; 
httppost.setHeader("Content-length",Integer.toString(text.length())); 
httppost.setEntity(new StringEntity(text)); 
HttpResponse response = httpclient.execute(httppost); 

當我試圖在eclipse上調試此代碼emulater一直運行,而調試器掛起。謝謝!

注:其掛在httpclient.execute(httppost)

+0

你能說出它掛在哪條線上嗎? –

+0

@KurtisNusbaum第二個片段的最後一行 –

+0

您是否驗證了仿真器與互聯網的連接? –

回答

3

這裏是我使用的Android POST請求的代碼:

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost("fullurl"); 

List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
pairs.add(new BasicNameValuePair("parameter", "variable"); 
post.setEntity (new UrlEncodedFormEntity(pairs)); 

HttpResponse response = client.execute(post); 

...等等。

+0

工作在您提供的代碼中的JSON請求不添加標頭。 –

0

您的意思是您的HttpPost路徑設置爲剛剛path。我認爲你的吊牌是因爲你沒有給HttpPost一個有效的URL。您需要修改此行:

HttpPost httppost = new HttpPost("path"); 

喜歡的東西

HttpPost httppost = new HttpPost("actual/url/path"); 
+0

我將路徑替換爲僅用於顯示目的的路徑。它不在我的soucr代碼 –

+0

我看到了,並且您確認該網址是有效的,並且正在使用您正在使用的計算機上工作? –

+0

它不是網址,它從我的機器 –

3

試試看:

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
JSONObject json = new JSONObject(); 
try{ 
     json.put("username", "Hello"); 
     json.put("password", "World"); 
     StringEntity se = new StringEntity(json.toString()); 
     se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
     post.setEntity(se); 
     HttpResponse response = httpclient.execute(httppost); 
     /*Checking response */ 
     if(response!=null){ 
      InputStream in = response.getEntity().getContent(); //Get the data in the entity 

} 
catch(Exception e){ 
    e.printStackTrace(); 
} 
0

你比JS版本有開始和你的文本字符串的結尾中的附加語言標記?

0
// Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(StringUrl); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
     nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 



     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 
     System.out.println("rep => " + response); 


    } catch (IOException e) { 
     System.out.println(e); 
    } 
}