Asyncktask向客户发送两个参数

时间:2016-05-30 06:35:29

标签: android android-asynctask

我有这个代码将一个param发送到客户端服务器并获得响应。 现在我有两个字符串类型的字符串发送我真的很困惑我的代码是什么?

protected String doInBackground(JSONObject... data)
    { 

     JSONObject json = data[0]; 

     HttpClient client = new DefaultHttpClient(); 
     HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000); 
     StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build()); 
     JSONObject jsonResponse = null; 

     HttpPost post = new HttpPost(url); 
     String resFromServer = ""; 

     try 
     { 
     StringEntity se = new StringEntity("json="+json.toString()); 

     post.addHeader("content-type", "application/x-www-form-urlencoded"); 

      post.setEntity(se); 

      HttpResponse response; 
      response = client.execute(post); 
      resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity()); 

     Log.i("Response from server", resFromServer); 

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


      return resFromServer; 

                         }
                             }

2 个答案:

答案 0 :(得分:0)

你必须创建JSONObject并将这两个字符串放入其中,并且必须将整个Object作为一个param传递:

JSONObject jsonObj = new JSONObject();
jsonObj.put("String1Key",string1);
jsonObj.put("String2Key",string2);

只需删除JSONObject json = data [0]行并添加它 它会起作用

顺便说一句,如果您正在使用doInBackground(JSONObject ... data)参数,那么将数据[0]和数据[1]作为参数传递给json.put

答案 1 :(得分:0)

您可以将帖子参数添加到您的网址

try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("parameter_name_1", "string1"));
nameValuePairs.add(new BasicNameValuePair("parameter_name_2", "string2"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(post);

 } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
 } catch (IOException e) {
// TODO Auto-generated catch block
 }

适当地替换parameter_name_1,parameter_name_2,string1和string2