无法将JSONObject从android发送到PHP



我正在尝试使用以下代码从android应用程序到php web应用程序发布JSONObject。

String url = "http://10.0.2.2/test/"
URL rest_url = new URL(url);
JSONObject params = new JSONObject();
params.put("username","admin"); 
// Send POST data request
BufferedReader reader=null;
DataOutputStream printout;
URLConnection conn = rest_url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( params.toString());
wr.close();

当我尝试在php中检索用户名时,我得到空值。

 <?php echo $_POST['username'];
 ?>

为了避免在每个类中为连接编写HTTP代码,我这样做了。

创建了单独的HTTP类,并放置了以下代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.util.Log;

public class HttpConnect
{
    HttpClient httpClient;
    String Url;
    private static final String                 DEBUG_TAG = "TAG";

    public HttpConnect(String url) {
        this.Url = url;
        httpClient = new DefaultHttpClient();
    }
    public HttpEntity Get() throws ClientProtocolException, IOException{
        HttpGet httpGet = new HttpGet(Url);
        HttpResponse httpResponseGet = httpClient.execute(httpGet);
        HttpEntity resEntityGet = httpResponseGet.getEntity();
        return resEntityGet;
    }
    public HttpEntity Post(HashMap<String, String> c) throws ClientProtocolException, IOException{
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(Url);
        // set up post data
        ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        Iterator<String> it = c.keySet().iterator();
        while (it.hasNext())
        {
            String key = it.next();
            nameValuePair.add(new BasicNameValuePair(key, c.get(key)));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
        HttpResponse httpResponseGet = httpClient.execute(httpPost);
        HttpEntity resEntityGet = httpResponseGet.getEntity();
        return resEntityGet;
    }
}

和从你的类访问这个类通过张贴你的键值数据在HashMap<String, String> obj = new HashMap<String, String>();

obj.put("username","admin");
HttpEntity resEntityGet = new HttpConnect("URL").Post(obj);

resEntityGet实体转换为字符串

String responseString = EntityUtils.toString(resEntityGet); //response returned from your script

你没有在Android代码上发送POST请求。您只是打印一个普通的String,在您的情况下是JSONObject。你需要做一些改动才能使它工作。

首先,设置你的conn发送一个POST

conn.setRequestMethod("POST");

然后,创建NameValuePairList。就像下面的例子。

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username", params.toString()));

现在使用我从这个答案中得到的方法。

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");
        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }
    return result.toString();
}

并按如下代码发送数据:

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(pairs));
writer.flush();
writer.close();
os.close();

EDIT:似乎NameValuePair在API 22上被弃用了,查看这个答案了解更多细节。

最新更新