目前我正在试图从和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文件I上$ _POST [ '车辆']做的回波,得到类似如下:

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

谁能告诉我在哪里,我错了,或者如果有更好的方法来实现什么,我试图做的?希望上面很有意义!

有帮助吗?

解决方案

经过大量的阅读和搜索我已经发现这个问题,我beleive在服务器上启用magic_quotes_gpc的幸福。

因此,使用:

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

在我的例子上述去除斜线并允许JSON来正确解码。

仍然不知道为什么发送StringEntity导致403错误?

其他提示

StringEntity s = new StringEntity(c.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
request.setEntity(s);

试试这个代码,它为我的作品

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) {
}

}

更改

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

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

当你试图参数发送到PHP脚本末问号是必要的。

<强>尝试此代码它完美

*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类这种的AsyncTask像这样:

私有类YourTask延伸的AsyncTask {         私人字符串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

    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top