2011-10-24 154 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); 
    } 
}