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.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?