Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Android中使用带有post参数的HttpClient和HttpPost_Java_Android_Json_Httpclient_Http Post - Fatal编程技术网

Java 在Android中使用带有post参数的HttpClient和HttpPost

Java 在Android中使用带有post参数的HttpClient和HttpPost,java,android,json,httpclient,http-post,Java,Android,Json,Httpclient,Http Post,我正在为一个Android应用程序编写代码,该应用程序应该获取数据,将其打包为Json,并将其发布到web服务器,而web服务器反过来应该使用Json进行响应 使用GET请求可以很好地工作,但是由于某些原因,使用POST似乎会剥离所有数据,而服务器不会接收任何内容 下面是一段代码: HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConn

我正在为一个Android应用程序编写代码,该应用程序应该获取数据,将其打包为Json,并将其发布到web服务器,而web服务器反过来应该使用Json进行响应

使用GET请求可以很好地工作,但是由于某些原因,使用POST似乎会剥离所有数据,而服务器不会接收任何内容

下面是一段代码:

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);        
DefaultHttpClient httpClient = new DefaultHttpClient(params);
BasicCookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);

String uri = JSON_ADDRESS;
String result = "";
String username = "user";
String apikey = "something";
String contentType = "application/json";

JSONObject jsonObj = new JSONObject();

try {
    jsonObj.put("username", username);
    jsonObj.put("apikey", apikey);
} catch (JSONException e) {
    Log.e(TAG, "JSONException: " + e);
}

HttpPost httpPost = new HttpPost(uri);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));
HttpGet httpGet = null;
try {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
    entity.setContentEncoding(HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    httpPost.setHeader("Content-Type", contentType);
    httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
    Log.e(TAG, "UnsupportedEncodingException: " + e);
}

try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();

    if (httpEntity != null) {
        InputStream is = httpEntity.getContent();
        result = StringUtils.convertStreamToString(is);
        Log.i(TAG, "Result: " + result);
    }
} catch (ClientProtocolException e) {
    Log.e(TAG, "ClientProtocolException: " + e);
} catch (IOException e) {
    Log.e(TAG, "IOException: " + e);
}

return result;
HttpParams params=new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(参数,5000);
HttpConnectionParams.setSoTimeout(参数,5000);
DefaultHttpClient httpClient=新的DefaultHttpClient(参数);
BasicCookieStore cookieStore=新BasicCookieStore();
httpClient.setCookieStore(cookieStore);
字符串uri=JSON_地址;
字符串结果=”;
字符串username=“user”;
字符串apikey=“某物”;
字符串contentType=“application/json”;
JSONObject jsonObj=新的JSONObject();
试一试{
jsonObj.put(“用户名”,username);
jsonObj.put(“apikey”,apikey);
}捕获(JSONException e){
Log.e(标记“JSONException:”+e);
}
HttpPost HttpPost=新的HttpPost(uri);
List postParams=new ArrayList();
add(新的BasicNameValuePair(“json”,jsonObj.toString());
HttpGet-HttpGet=null;
试一试{
UrlEncodedFormEntity实体=新的UrlEncodedFormEntity(后参数);
setContentEncoding(HTTP.UTF_8);
entity.setContentType(“应用程序/json”);
httpPost.setEntity(实体);
setHeader(“内容类型”,contentType);
setHeader(“接受”,contentType);
}捕获(不支持的编码异常e){
Log.e(标签“UnsupportedEncodingException:”+e);
}
试一试{
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
if(httpEntity!=null){
InputStream=httpEntity.getContent();
结果=StringUtils.convertStreamToString(is);
Log.i(标签,“结果:+结果”);
}
}捕获(客户端协议例外e){
Log.e(标签“ClientProtocolException:”+e);
}捕获(IOE异常){
Log.e(标记“IOException:+e);
}
返回结果;
我想我已经遵循了关于如何创建参数和发布参数的一般指导原则,但显然没有


在这一点上,我非常欢迎任何帮助或指向我可以找到解决方案的指针(在花了几个小时意识到没有发送post数据之后)。真正的服务器在Tomcat上运行Wicket,但我也在一个简单的PHP页面上进行了测试,没有任何区别。

您是否尝试过在没有JSON对象的情况下运行Wicket,并且只传递了两个basicnamevaluepairs? 此外,它可能与您的服务器设置有关

更新: 这是我使用的一段代码:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }
InputStream=null;
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“lastupdate”,lastupdate));
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(连接);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
Log.d(“HTTP”,“HTTP:OK”);
}捕获(例外e){
Log.e(“HTTP”,“HTTP连接中的错误”+e.toString());
}

我刚刚检查了一下,我的代码与您的代码相同,它运行得非常好。 唯一的区别是我如何填写参数列表:

我使用:
ArrayList参数

然后这样填充:

 params.add(new BasicNameValuePair("apikey", apikey);
我不使用任何JSONObject向Web服务发送参数


您必须使用JSONObject吗?

您实际上可以通过以下方式将其作为JSON发送:

// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// 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);

公共类GetUsers扩展异步任务{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        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();
    }

    public String connect()
    {
        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpPost htopost = new HttpPost("URL");
        htopost.setHeader(new BasicHeader("Authorization","Basic Og=="));

        try {

            JSONObject param = new JSONObject();
            param.put("PageSize",100);
            param.put("Userid",userId);
            param.put("CurrentPage",1);

            htopost.setEntity(new StringEntity(param.toString()));

            // Execute the request
            HttpResponse response;

            response = httpclient.execute(htopost);
            // Examine the response status
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result = convertStreamToString(instream);

                // A Simple JSONObject Creation
                json = new JSONArray(result);

                // Closing the input stream will trigger connection release
                instream.close();
                return ""+response.getStatusLine().getStatusCode();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected String doInBackground(String... urls) {
        return connect();
    }

    @Override
    protected void onPostExecute(String status){
        try {

            if(status.equals("200"))
            {

                    Global.defaultMoemntLsit.clear();

                    for (int i = 0; i < json.length(); i++) {
                        JSONObject ojb = json.getJSONObject(i);
                        UserMomentModel u = new UserMomentModel();
                        u.setId(ojb.getString("Name"));
                        u.setUserId(ojb.getString("ID"));


                        Global.defaultMoemntLsit.add(u);
                    }




                            userAdapter = new UserAdapter(getActivity(), Global.defaultMoemntLsit);
                            recycleView.setAdapter(userMomentAdapter);
                            recycleView.setLayoutManager(mLayoutManager);
           }



        }
        catch (Exception e)
        {
            e.printStackTrace();

        }
    }
}
@覆盖
受保护的void onPreExecute(){
super.onPreExecute();
}
私有字符串convertStreamToString(InputStream为){
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
公共字符串连接()
{
HttpClient HttpClient=新的DefaultHttpClient();
//准备一个请求对象
HttpPost htopost=新的HttpPost(“URL”);
htopost.setHeader(新的基本阅读器(“授权”,“基本Og=”));
试一试{
JSONObject参数=新的JSONObject();
参数put(“页面大小”,100);
参数put(“Userid”,Userid);
参数put(“当前页面”,1);
htopost.setEntity(新的StringEntity(param.toString());
//执行请求
HttpResponse响应;
response=httpclient.execute(htopost);
//检查响应状态
//获取响应实体
HttpEntity=response.getEntity();
如果(实体!=null){
//一个简单的JSON响应读取
InputStream instream=entity.getContent();
字符串结果=convertStreamToString(流内);
//一个简单的JSONObject创建
json=新的JSONArray(结果);
//关闭输入流将触发连接释放
流内关闭();
返回“”+response.getStatusLine().getStatusCode();
}
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的字符串doInBackground(字符串…URL){
返回连接();
}
@凌驾
受保护的void onPostExecute(字符串状态){