douzhuo6931 2011-03-14 03:22
浏览 34
已采纳

将原始格式的数据发布到PHP文件并获得响应

I am making an android application where I need to send some data collected from a data to server php file using post data and get the echoed text from the php file and display it. I have the post variables in this format -> "name=xyz&home=xyz" and so on. I am using the following class to post, but the php file on the server does not get the post vars. Can someone please tell me whats wrong or any other ways to do what I am trying to do?

package xxx.xxx.xxx;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtil {
    public static String UrlToString(String targetURL, String urlParameters)
      {
        URL url;
        HttpURLConnection connection = null;  
        try {
          //Create connection
          url = new URL(targetURL);
          connection = (HttpURLConnection)url.openConnection();
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type", 
               "application/x-www-form-urlencoded");

          connection.setRequestProperty("Content-Length", "" + 
                   Integer.toString(urlParameters.getBytes().length));
          connection.setRequestProperty("Content-Language", "en-US");  

          connection.setUseCaches (false);
          connection.setDoInput(true);
          connection.setDoOutput(true);

          //Send request
          DataOutputStream wr = new DataOutputStream (
                      connection.getOutputStream ());
          wr.write(urlParameters.getBytes("UTF-8"));
          wr.flush ();
          //Get Response    
          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer(); 
          while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('');
          }
          rd.close();
          return response.toString();

        } catch (Exception e) {

          e.printStackTrace();
          return null;

        } finally {

          if(connection != null) {
            connection.disconnect(); 
          }
        }
      }

}

I get a response from php file, but the php file does not get the post data.

  • 写回答

1条回答 默认 最新

  • drfls28608 2011-03-14 03:33
    关注

    The example looks okay to me for a beginner. Only the following springs out:

    connection.setRequestProperty("Content-Length", "" + 
        Integer.toString(urlParameters.getBytes().length));
    

    and

    wr.write(urlParameters.getBytes("UTF-8"));
    

    In the first you're converting chars to bytes using platform default encoding. The resulting length is not necessarily the same as when using UTF-8 encoding to convert chars to bytes as you did when writing the request body. So the chance exist that the Content-Length header is off from the actual content length. To fix this, you should be using the same charset on the both calls.

    But I believe that PHP isn't really that strict when parsing the request body so that you would get nothing in the PHP end. Probably the urlParameters is not in proper format. Are they really URL-encoded?

    Anyway, did you try it with Android's builtin HttpClient API? It should be as simple as follows:

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(targetURL);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("name", "xyz"));
    params.add(new BasicNameValuePair("home", "xyz"));
    post.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse response = client.execute(post);
    InputStream input = response.getEntity().getContent();
    // ...
    

    If that doesn't work as well, then the mistake is likely in the PHP side.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧