2013-07-31 43 views
0

我已经使用了大约5种方式将JSON数据发布到HTTP请求URL,但没有获得成果,它没有发布JSON格式,因为我想要的,下面在JSON中要发送的即时通讯目前全成使用HTML发送它:使用http发布JSON,fedup和失败

这是我想要的JSON: { “X”: “N”, “Y”: “55”}

这里是我的成功合作HTML代码:

<html><head><script> 
function sendForm(form) 
{ 
     // Construct the JSON string in form.value 
     // x is a string ('cos of the quotes) 
     // y is an integer ('cos of no quotes) 
     form.value.value = "{ \"x\": \"" + form.example1.value + "\", \"y\": " + form.example2.value + " }" 
     form.submit(); 
} 
</script></head> 
<body> 
<form action="https://api.winv.com/v1/4bhj/306adk" method="post"> 
<input type="hidden" name="value"> 
string:<input type="text" name="example1"> 
number:<input type="text" name="example2"> 
<input type="button" value="Submit" onClick="sendForm(this.form);"> 
</form> 
    </body> 
</html> 

我试过的代码(它的所有功能)

public void xyz() { 
     try { 
      JSONObject json = new JSONObject(); 
      json.put("x", "Nishant"); 
      json.put("y", 34567); 
      HttpParams httpParams = new BasicHttpParams(); 
      HttpConnectionParams.setConnectionTimeout(httpParams, 
        10000); 
      HttpConnectionParams.setSoTimeout(httpParams, 10000); 
      HttpClient client = new DefaultHttpClient(httpParams); 
      // 
      //String url = "http://10.0.2.2:8080/sample1/webservice2.php?" + 
      //    "json={\"UserName\":1,\"FullName\":2}"; 
      String url = "url"; 

      HttpPost request = new HttpPost(url); 
      request.setEntity(new ByteArrayEntity(json.toString().getBytes(
        "UTF8"))); 
      request.setHeader("json", json.toString()); 
      HttpResponse response = client.execute(request); 
      HttpEntity entity = response.getEntity(); 
      // If the response does not enclose an entity, there is no need 

     } catch (Throwable t) { 
      Toast.makeText(this, "Request failed: " + t.toString(), 
        Toast.LENGTH_LONG).show(); 
     } 
    } 

    public void getServerData() throws JSONException, ClientProtocolException, 
      IOException { 

     HttpParams httpParams = new BasicHttpParams(); 
     HttpConnectionParams.setConnectionTimeout(httpParams, 10000); 
     HttpConnectionParams.setSoTimeout(httpParams, 10000); 
     HttpClient client = new DefaultHttpClient(httpParams); 
     HttpPost request = new HttpPost(
       "url"); // add 
                         // your 
                         // url 
                         // here... 

     request.setHeader("Content-Type", "application/json"); 

     JSONObject json = new JSONObject(); 
     json.put("y", "55"); 
     json.put("x", "Nishant"); 
     Log.i("jason Object", json.toString()); 

     StringEntity se = new StringEntity(json.toString()); 

     se.setContentEncoding("UTF-8"); 
     se.setContentType("application/json"); 

     request.setEntity(se); 

     HttpResponse response = client.execute(request); 

     HttpEntity entity = response.getEntity(); 
     InputStream is = entity.getContent(); 
     String _response = convertStreamToString(is); 
     System.out.println("res-- " + _response); 

     // Check if server response is valid code 
     int res_code = response.getStatusLine().getStatusCode(); 
     System.out.println("code-- " + res_code); 
    } 

    private static String convertStreamToString(InputStream is) { 

     BufferedReader reader = new BufferedReader(new InputStreamReader(is), 
       8192); 
     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 void postData() { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(
       "url"); 

     try { 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("", "Nishant")); 
      nameValuePairs.add(new BasicNameValuePair("x:", "45")); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 
    } 

    protected void sendJson(final String email, final int pwd) { 
     Thread t = new Thread() { 

      public void run() { 
       Looper.prepare(); // For Preparing Message Pool for the child 
            // Thread 
       HttpClient client = new DefaultHttpClient(); 
       HttpConnectionParams.setConnectionTimeout(client.getParams(), 
         10000); // Timeout Limit 
       HttpResponse response; 
       JSONObject json = new JSONObject(); 

       try { 
        HttpPost post = new HttpPost(
          "url"); 
        json.put("x", email); 
        json.put("y", pwd); 
        StringEntity se = new StringEntity(json.toString()); 
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, 
          "application/json")); 
        post.setEntity(se); 
        response = client.execute(post); 

        /* Checking response */ 
        if (response != null) { 
         InputStream in = response.getEntity().getContent(); // Get 
                      // the 
                      // data 
                      // in 
                      // the 
                      // entity 
        } 

       } catch (Exception e) { 
        e.printStackTrace(); 
        // createDialog("Error", "Cannot Estabilish Connection"); 
       } 

       Looper.loop(); // Loop in the message queue 
      } 
     }; 

请告诉我为什么不发帖?哪里可能做错了?

+0

你会用'json.toString()'得到什么?你能检查并告诉吗?因为在制作网址时可能会有一些错误。 你确定你是在不同的线程上执行此操作吗? –

+0

我也尝试过线程,因为您可以在代码上面看到代码但仍然无法运行 – Naaz

+0

我看不到任何线程或异步。 CAn您粘贴错误 –

回答

1

看起来像很多代码。我想你会更好地将JSON对象封装在一个单独的方法中,然后可能使用下面的例子,这对我来说非常适用。你似乎有很多,我不认为是必要的HTTP连接对象......

public static boolean sendJSONtoBLX(String path, JSONObject json) 
     throws Exception { 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httpost = new HttpPost(path); 
    StringEntity se = new StringEntity(json.toString()); 
    httpost.setEntity(se); 
    httpost.setHeader("Accept", "application/json"); 
    httpost.setHeader("Content-type", "application/json"); 
    @SuppressWarnings("rawtypes") 
    ResponseHandler responseHandler = new BasicResponseHandler(); 
    @SuppressWarnings("unchecked") 
    String response = httpclient.execute(httpost, responseHandler); 
    JSONObject jsonResponse = new JSONObject(response); 
    String serverResponse = jsonResponse.getString("success"); 

    if (serverResponse.equals("true")) { 
     return true; 
    } else { 
     return false; 
    } 
} 

我创建JSON对象有:

public final static JSONObject writeJSON() throws Exception { 
    JSONObject obj = new JSONObject(); 
    try { 
     obj.put("x", "Nishant"); 
     obj.put("y", 34567); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return obj; 
} 

新信息:经过测试在本地,这看起来是Android不访问https的SSL问题。无关JSON等。上面的答案适用于普通http。

+0

我应该通过什么(url,JSON_object?)sendJSONtoBLX(String path,JSONObject json) – Naaz

+0

该URL将是https:// api .winv.com/v1/4bhj/306adk我想,看看你的HTML代码。在我提供的例子中,json对象只是writeJSON()的输出。 – iaindownie

+0

仍然面临问题,JSON提供给api链接,所以我甚至可以检查实际发布的内容 – Naaz

0

只是把这个代码代码:

StringEntity oStringEntity = new StringEntity(json.toString()); 
oStringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
request.setEntity(oStringEntity); 

取而代之的是:

request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8"))); 
request.setHeader("json", json.toString()); 

如果这解决您的问题,那么只需PLZ接受它!

+0

让我试试 – Naaz

+0

它没有工作提供相同的问题 – Naaz