2015-09-13 51 views
1

我正尝试使用以下代码将JSONObject从android应用程序发布到php web应用程序。无法将JSONObject从Android发布到PHP

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']; 
?> 

回答

4

您没有在您的Android代码上发送POST请求。你只是打印一个普通的String,你的情况是你的JSONObject。你必须改变一些东西才能工作。

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

conn.setRequestMethod("POST"); 

然后,创建的NameValuePair一个List。像下面的例子。

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

现在用这个方法我已经从this answer拍摄。

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(); 

编辑:似乎NameValuePair是在API 22弃用,检查this answer了解更多详情。

7

为了避免在每个类中编写HTTP代码来进行连接,我这样做了。在HashMap<String, String> obj = new HashMap<String, String>();

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

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; 

    } 

} 

,并从你的类访问该类张贴您的键值数据resEntityGet entitiy转换为由字符串,如:

创建单独的HTTP类,并把这个代码这

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

这也是一个很好的解决方案。但据我所知,apache http客户端不再支持。 – Mauker