【问题标题】:Android HttpClient, DefaultHttpClient, HttpPostAndroid HttpClient、DefaultHttpClient、HttpPost
【发布时间】:2012-10-16 04:48:26
【问题描述】:

如何将字符串数据 (JSONObject.toString()) 发送到 url。我想在 util 类中编写一个静态方法来执行此操作。我希望方法签名如下

public static String postData (String url, String postData) throws SomeCustomException

字符串url应该是什么格式

返回字符串是来自服务器的响应,作为 json 数据的字符串表示。

编辑

当前连接工具

package my.package;
import my.package.exceptions.CustomException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;


 public class ConnectionUtil {

 public static String postData(String url, String postData)
        throws CustomException {

    // Create a new HttpClient and Post Header
    InputStream is = null;
    StringBuilder sb = null;
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost();
    httppost.setHeader("host", url);

    Log.v("ConnectionUtil", "Opening POST connection to URI = " + httppost.getURI() + " url = " + URLDecoder.decode(url));

    try {
        httppost.setEntity(new StringEntity(postData));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
        e.printStackTrace();
        throw new CustomException("Could not establish network connection");
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line = "0";

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
        throw new CustomException("Error parsing the response");
    }
    Log.v("ConnectionUtil", "Sent: "+postData);
    Log.v("ConnectionUtil", "Got result "+result);
    return result;

}

}

Logcat 输出

10-16 11:27:27.287:E/log_tag(4935):http 连接出错 java.lang.NullPointerException 10-16 11:27:27.287: W/System.err(4935): java.lang.NullPointerException 10-16 11:27:27.287: W/System.err(4935): 在 org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496) 10-16 11:27:27.307: W/System.err(4935): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 10-16 11:27:27.327: W/System.err(4935): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 10-16 11:27:27.327: W/System.err(4935): 在 in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92) 10-16 11:27:27.327: W/System.err(4935): 在 in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:54) 10-16 11:27:27.327: W/System.err(4935): 在 in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:1) 10-16 11:27:27.327: W/System.err(4935): 在 android.os.AsyncTask$2.call(AsyncTask.java:185) 10-16 11:27:27.327: W/System.err(4935): 在 java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 10-16 11:27:27.327: W/System.err(4935): 在 java.util.concurrent.FutureTask.run(FutureTask.java:138) 10-16 11:27:27.327: W/System.err(4935): 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 10-16 11:27:27.327: W/System.err(4935): 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 10-16 11:27:27.327: W/System.err(4935): 在 java.lang.Thread.run(Thread.java:1019) 10-16 11:27:27.327: V/log_tag(4935): 无法建立网络连接

【问题讨论】:

  • 我认为您的 POST 方法将 StringEntity 发送到服务器端存在一些问题。查看我的最新答案,看看它是否有效..

标签: android apache-httpclient-4.x


【解决方案1】:

我认为在您的代码中,基本问题是由您在 url 中使用 StringEntityPOST 参数的方式引起的。检查以下代码是否有助于使用 StringEntity 将数据发布到服务器。

    // Build the JSON object to pass parameters
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("username", username);
    jsonObj.put("data", dataValue);

    // Create the POST object and add the parameters
    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(httpPost);

希望这有助于解决您的问题。谢谢。

【讨论】:

  • 嗨。我认为这有帮助,但我仍然收到运行时错误 UnknownHostException。我确定我的网址有效并从我的浏览器中检查过。对于 google.com 或 example.com,我也遇到同样的错误。我应该如何格式化 URL/URI?我想点击 URL http://xyz.mysite.com/some_page.php/ 并发布数据。我还需要指定端口吗?
  • 只使用 80。所以这应该是默认值。这现在正在工作并击中服务器。谢谢。
【解决方案2】:

嗯,以下是我对你的问题的看法:-

  1. 首先,您应该使用POST 方法简单地将数据发送到服务器。它在 Android 中也很容易且绝对可行。发送POST数据的简单代码sn-p可以是这样的:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://yourserverIP/postdata.php");
    String serverResponse = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("datakey1", dataValue1));
        nameValuePairs.add(new BasicNameValuePair("datakey2",
                dataValue2));
    
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
    
        serverResponse = response.getStatusLine().toString();
        Log.e("response", serverResponse);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    以上代码将数据发送到您服务器上的 PHP 脚本postdata

  2. 接下来,为了解析服务器发送的JSON数据,您可以使用JSONParser,然后根据您的需要轻松使用它。您可以使用以下代码获取服务器返回的响应:

    String jsonData = EntityUtils.toString(serverResponse.getEntity());
    

希望这会有所帮助。谢谢。

【讨论】:

  • 我没有使用表单。服务器只想查看字符串数据。就是这样。
  • @phodu_insaan 即使是发送字符串数据,您也需要将 POST 数据发送到服务器。因此,您无需使用表单将字符串数据发送到服务器。如果你只是想发送命令,比如只向服务器传递一个参数,那么你也可以考虑使用 GET 方法。我也可以帮你搞定 GET。
  • 我在做几乎同样的事情。我没有传递UrlEncodedFormEntity,而是使用我的字符串数据传递new StringEntity。我得到一个NullPointerException。只需将我的 logcat 输出附加到问题中即可。
  • 是的,请在此处添加您的 LogCat 输出。我无法找到您,您是如何传递 StringEntity 的?请添加执行此任务的代码。这将有助于更好地理解您的问题。
【解决方案3】:

尝试使用此方法,其中 strJsonRequest 是您要发布的 json 字符串,而 strUrl 是您要发布 strJsonRequest 的 url

   public String urlPost(String strJsonRequest, String strURL) throws Exception 
{
    try
    {
        URL objURL = new URL(strURL);
        connection = (HttpURLConnection)objURL.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setAllowUserInteraction(false);
        connection.setUseCaches(false);
        connection.setConnectTimeout(TIMEOUT_CONNECT_MILLIS);
        connection.setReadTimeout(TIMEOUT_READ_MILLIS);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept-Charset", "utf-8");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setRequestProperty("Content-Length", ""+strJsonRequest.toString().getBytes("UTF8").length);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        byte [] b = strJsonRequest.getBytes("UTF-8");

        outputStream.write(b);
        outputStream.flush();

        inputstreamObj = (InputStream) connection.getContent();//getInputStream();

        if(inputstreamObj != null)
            strResponse = convertStreamToString(inputstreamObj);

    }
    catch(Exception e)
    {
        throw e;
    }
    return strResponse;
}

convertStreamToString()方法如下

private static String convertStreamToString(InputStream is)
{
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    StringBuilder sb = new StringBuilder();

    String line = null;
    try
    {
        while ((line = reader.readLine()) != null) 
        {
            sb.append(line + "\n");
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    finally 
    {
        try 
        {
            is.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

【讨论】:

  • converStreamToString是什么方法?
  • url 格式应该是什么?我收到了MalformedURLException
  • 不确定您在 logcat 中获取的 url 是什么,一旦检查它是否与您传递的相同
【解决方案4】:

根据您的服务器端代码的设置方式,您的服务器有一个用于处理 API 调用的 php 页面的 URL 示例格式为:

http://yoururl.com/demo.php?jsondata=postData

如果您使用的是帖子连接,您可以简单地说:

http://yoururl.com/demo.php

并将您的帖子参数传递给它,即 json 字符串

这里有一个很棒的教程,教你如何做到这一点: http://yoururl.com/demo.php?jsondata=postData

【讨论】:

  • 服务器接受后连接。所以我只需要像http://www.example.com/my_page.php 这样的网址,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多