Android HttpClient, DefaultHttpClient, HttpPost

7

我要如何将一个字符串数据 (JSONObject.toString()) 发送到一个 URL 上。我想在一个工具类中编写一个静态方法来完成此操作。我希望该方法签名如下

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到服务器端存在一些问题。查看我的最新答案,看看是否有效。 - Shekhar Chikara
4个回答

2
好的,以下是我对你的问题的想法:

首先,我们需要了解IT技术的一些基本概念。

  1. First, you should simply send the data to the server by using POST method. Its easy and absolutely possible in Android also. A simple code snippet for sending POST data can be like:

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

    The above code sends data to a PHP script postdata on your server.

  2. Next, for parsing the JSON data sent by the server, you can use a JSONParser and then easily utilize it as per your needs. You can get the response returned from the server by using the following code:

    String jsonData = EntityUtils.toString(serverResponse.getEntity());
    
希望这可以帮到您。谢谢。

我没有使用表单,服务器只需要查看字符串数据,仅此而已。 - kapad
@phodu_insaan 即使是发送字符串数据,您也需要向服务器发送POST数据。因此,您不需要使用表单将字符串数据发送到服务器。如果您只想发送像传递一个参数这样的命令,则可以考虑使用GET方法。我也可以帮您使用GET。 - Shekhar Chikara
我正在做几乎相同的事情。不过我传递的是一个带有字符串数据的new StringEntity,而不是一个UrlEncodedFormEntity。我遇到了一个空指针异常。我将我的logcat输出附加到问题中。 - kapad
请在此处添加您的LogCat输出。我不明白您是如何传递StringEntity的,请添加执行此任务的代码。这将有助于更好地理解您的问题。 - Shekhar Chikara

2

我认为你的代码中基本问题是由于使用StringEntity将参数POST到URL的方式引起的。请检查以下代码,以了解如何使用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。我确定我的URL有效,并从浏览器中进行了检查。我也会在google.com或example.com上收到相同的错误。我应该如何格式化URL / URI?我想访问URL http://xyz.mysite.com/some_page.php/ 并发布数据。我需要指定端口吗? - kapad
只使用80端口。这应该是默认的。现在它正在工作并连接到服务器。谢谢。 - kapad

1

尝试使用此方法,其中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 方法? - kapad
应该使用什么样的URL格式?我遇到了“MalformedURLException”错误。 - kapad
我不确定您在logcat中获取的URL是什么,请检查一下是否与您传递的相同。 - G_S

0
根据您的服务器端代码设置,处理API调用的php页面所在的URL示例格式可能如下:
http://yoururl.com/demo.php?jsondata=postData

如果您正在使用POST连接,您可以简单地说:
http://yoururl.com/demo.php

并将其传递你的帖子参数,即Json字符串

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


服务器接受POST连接。所以我只需要像http://www.example.com/my_page.php这样的URL,对吗? - kapad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接