2016-08-23 1 views
0
public static JSONObject getJSONfromURL(String url) { 
    JSONObject jArray = null; 
    String idTosend; 
    String _accessToken = "saasfcsaas" 

    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httpPostRequest = new HttpPost(url); 
    StringEntity se = null;  

    try { 
     se = new StringEntity(_accessToken); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } 

    httpPostRequest.addHeader("X-Auth-Token", _accessToken); 

    httpPostRequest.setEntity(se); 

    HttpResponse response = null; 
    try { 
     List<NameValuePair> nameValuePairs = new ArrayList<>(); 
     nameValuePairs.add(new BasicNameValuePair("Id",idTosend)); 

     httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     response = httpclient.execute(httpPostRequest); 

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


    Here I am sending token as a header and Id as a parameter. 

Приведенный выше код работает, но без заголовка. Поля, требующие отображения заголовка, возвращают значение null.Как отправить токен как заголовок и идентификатор в качестве параметра в Http Post request?

Пожалуйста, дайте мне знать, что не так в коде.

+0

AFAIK метод называется 'setHeader' вместо' addHeader' см Http: // stackoverflow.com/questions/12358045/java-httppost-request-with-apache-httpclient – devnull69

+0

вы можете использовать volley lib для этого. –

ответ

0

Попробуйте следующее:

URL url; 
    StringBuilder sb = new StringBuilder(); 
    sb.append(""); 
    try { 
     url = new URL("URL"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("POST"); 
     conn.setUseCaches(false); 
     conn.setDoInput(true); 

     conn.setRequestProperty("X-Auth-Token", _accessToken); 

     conn.setDoOutput(true); 
     OutputStream os = conn.getOutputStream(); 
     BufferedWriter writer = new BufferedWriter(
       new OutputStreamWriter(os, "UTF-8")); 

     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("Id",idTosend)); 

     writer.write(getQuery(params)); 
     writer.flush(); 
     writer.close(); 
     os.close(); 

     conn.connect(); 

     STATUS = conn.getResponseCode(); 

     if(STATUS == 200 || STATUS == 201) 
      reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     else 
      reader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); 

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

     Log.e(TAG, "response: " + sb.toString()); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 


private String getQuery(List<NameValuePair> params) throws  UnsupportedEncodingException{ 
    StringBuilder result = new StringBuilder(); 
    boolean first = true; 

    for (NameValuePair pair : params) 
    { 
     if (first) 
      first = false; 
     else 
      result.append("&"); 

     result.append(URLEncoder.encode(pair.getName(), "UTF-8")); 
     result.append("="); 
     result.append(URLEncoder.encode(pair.getValue(), "UTF-8")); 
    } 

    return result.toString(); 
} 

Для лучшей практики, попробуйте использовать Retrofit

+0

ok попробует это, а также Retrofit.thanks.Will дайте знать, если получите какие-либо ошибки. –

Смежные вопросы