代码之家  ›  专栏  ›  技术社区  ›  Scoobler

android json httpclient使用httpresponse向php服务器发送数据

  •  23
  • Scoobler  · 技术社区  · 16 年前

    我正在尝试从和android应用程序向php服务器发送一些数据(两者都由我控制)。

    应用程序中的表单上收集了大量数据,这些数据将写入数据库。这都管用。

    在我的主代码中,首先我创建了一个jsonobject(在本例中,我在这里对它进行了裁剪):

    JSONObject j = new JSONObject();
    j.put("engineer", "me");
    j.put("date", "today");
    j.put("fuel", "full");
    j.put("car", "mine");
    j.put("distance", "miles");
    

    接下来,我将对象传递给发送,并接收响应:

    String url = "http://www.server.com/thisfile.php";
    HttpResponse re = HTTPPoster.doPost(url, j);
    String temp = EntityUtils.toString(re.getEntity());
    if (temp.compareTo("SUCCESS")==0)
    {
        Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();
    }
    

    HttpPoster类:

    public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        HttpEntity entity;
        StringEntity s = new StringEntity(c.toString());
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        entity = s;
        request.setEntity(entity);
        HttpResponse response;
        response = httpclient.execute(request);
        return response;
    }
    

    这将得到一个响应,但服务器将返回一个403禁止的响应。

    我试着改变dopost函数一点(这实际上更好一点,正如我所说,我有很多要发送的,基本上是同一个表单的3个不同的数据-所以我创建了3个jsonobjects,每个表单条目一个-条目来自db,而不是我使用的静态示例)。

    首先我把电话改了一下:

    String url = "http://www.myserver.com/ServiceMatalan.php";
    Map<String, String> kvPairs = new HashMap<String, String>();
    kvPairs.put("vehicle", j.toString());
    // Normally I would pass two more JSONObjects.....
    HttpResponse re = HTTPPoster.doPost(url, kvPairs);
    String temp = EntityUtils.toString(re.getEntity());
    if (temp.compareTo("SUCCESS")==0)
    {
        Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();
    }
    

    好的,对dopost函数的更改:

    public static HttpResponse doPost(String url, Map<String, String> kvPairs) throws ClientProtocolException, IOException 
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        if (kvPairs != null && kvPairs.isEmpty() == false) 
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
            String k, v;
            Iterator<String> itKeys = kvPairs.keySet().iterator();
            while (itKeys.hasNext()) 
            {
                k = itKeys.next();
                v = kvPairs.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }             
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
        HttpResponse response;
        response = httpclient.execute(httppost);
        return response;
    }
    

    好的,这返回一个响应200

    int statusCode = re.getStatusLine().getStatusCode();
    

    但是,服务器上接收到的数据无法解析为json字符串。我认为格式不好(这是我第一次使用json):

    如果在php文件中,我在$_post['vehicle']上执行echo,会得到以下结果:

    {\"date\":\"today\",\"engineer\":\"me\"}
    

    有谁能告诉我哪里出错了,或者有没有更好的方法来实现我的目标?希望上面说的有道理!

    5 回复  |  直到 9 年前
        1
  •  11
  •   Scoobler    16 年前

    经过大量的阅读和搜索,我发现了问题所在,我相信magic_quotes_gpc正在服务器上启用。

    因此,使用:

    json_decode(stripslashes($_POST['vehicle']));
    

    在上面的示例中,删除斜杠并允许正确解码json。

    仍然不确定为什么发送stringentity会导致403错误?

        2
  •  4
  •   Bill the Lizard    15 年前
    StringEntity s = new StringEntity(c.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");
    request.setEntity(s);
    
        3
  •  1
  •   Sachin Gurnani    14 年前

    试试这个代码它对我有用

    public void postData(String result,JSONObject obj) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    
    String json=obj.toString();
    
    try {
    
        HttpPost httppost = new HttpPost(result.toString());
        httppost.setHeader("Content-type", "application/json");
    
        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se); 
    
        HttpResponse response = httpclient.execute(httppost);
        String temp = EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);
    
    
    } catch (ClientProtocolException e) {
    
    } catch (IOException e) {
    }
    

    }

        4
  •  0
  •   Scoobler    14 年前

    变化

    (String url = "http://www.server.com/MainPage.php";)
    

    (String url = "http://www.server.com/MainPage.php?";)
    

    当您试图将参数发送到php脚本时,末尾的问号是必需的。

        5
  •  0
  •   Nur Gazi    9 年前

    试试这个代码,它工作得很好

    *For HttpClient class* download jar file "httpclient-4.3.6.jar" and put in libs folder then
    Compile:   dependencies {compile files('libs/httpclient-4.3.6.jar')}
    
    repositories {
            maven {
                url "https://jitpack.io"
            }
        }

    然后将httpclient类调用此异步任务,如下所示:

    yourtask扩展了asynctask{ private string error_msg=“服务器错误!”;

        private JSONObject response;
    
    
    
        @Override
        protected Boolean doInBackground(String... params) {
            try {
                JSONObject mJsonObject = new JSONObject();
                mJsonObject.put("user_id", "user name");
                mJsonObject.put("password", "123456");
                String URL=" Your Link"
    
                //Log.e("Send Obj:", mJsonObject.toString());
    
                response = HttpClient.SendHttpPost(URL, mJsonObject);
                boolean status = response != null && response.getInt("is_error") == 0; // response
    
                return status;
            } catch (JSONException | NullPointerException e) {
                e.printStackTrace();
                mDialog.dismiss();
                return false;
            }
        }
    
        @Override
        protected void onPostExecute(Boolean status) {
           // your code
    
        }
    }