当前位置: 首页 > 知识库问答 >
问题:

Android HttpClient,默认HttpClient,HttpPost

公羊俭
2023-03-14

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

公共静态字符串 postData (String url, String postData) 抛出 SomeCustomException

字符串url的格式应该是什么

返回的 String 是来自 服务器的响应,作为 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;

}

}

共有3个答案

万俟渝
2023-03-14

尝试使用此方法,其中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();
}
越文康
2023-03-14

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

> < li>

首先,您应该使用< code>POST方法将数据发送到服务器。这很容易,在Android系统中也绝对可行。发送< code>POST数据的简单代码片段如下:

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脚本< code>postdata。

String jsonData = EntityUtils.toString(serverResponse.getEntity());
寇夜洛
2023-03-14

我认为在您的代码中,基本问题是由您使用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);

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

 类似资料:
  • 我正在Micronaut中编写一个java库模块,它有一个http客户端。这个想法是我的微服务将使用这个库作为jar依赖项并使用http客户端。 问题陈述:我想在不使用 的情况下配置我的 HttpClient。 为什么我不想用application.yml?-因为使用此库的微服务也将拥有自己的< code>application.yml,并且在构建jar时,需要合并两个< code>applica

  • 问题内容: 两者之间有很大的区别,最好使用哪一个? 问题答案: :Apache的子类,配置了合理的默认设置和Android的注册方案,并允许用户添加类。该客户端处理cookie,但默认情况下不保留它们。要保留Cookie,只需将Cookie存储添加到 [ API ]

  • 我正在Java控制台应用程序中使用ApacheHttpClient 4.5(具有fluent接口)。我注意到,它的默认超时值似乎是无限的,但我必须为我发送的请求使用非无限超时值。我想对所有请求使用相同的超时值。 如何全局设置默认的连接超时和套接字超时值,以便不必在代码中发送请求的每个位置都设置它们?(记住我使用的是流畅的界面) 示例: 现在,在我的代码中发送请求的每个地方,我都会执行如下操作:(简

  • 我目前正在使用vscode和apachepoi,创建了一个程序来自动创建<code>。xlsx编程并让A1单元输入一个名为“Tester”的字符串,然后弹出错误。 我程序中的代码: 错误代码: 嗯.xml( Apache POI对我来说是新的,请帮助我,我会非常感激,非常感谢。

  • 入口方法或适配器或其他原因导致异常时需要走的视图,依然是打开MainModule,加入代码 @Fail("jsp:jsp.500") 含义就是内部重定向到/WEB-INF/jsp/500.jsp页面 打开web.xml, 加入如下配置 <error-page> <error-code>500</error-code> <location>/WEB-INF/

  • 这个项目以json交互为主,所以,默认用json视图好了. 打开MainModule,加入代码 @Ok("json:full") 这里的json指UTF8JsonView类, 后面的full是JsonFormat的其中一种内置格式的缩写: 默认 -- 忽略空值,换行,key不带双引号, 新版jquery不兼容 full -- 不忽略空值,换行,key带双引号, 新版jquery兼容 compac