2014-12-24 151 views
2

從我的Android應用程序中,我想請求帶有GET參數的URL並閱讀響應。在要求我必須添加一個兩個頭的參數(鍵和DT)。我寫了一些代碼,但我有404個error.this是我的源android發送帶有標頭的HTTP GET請求

public class MainActivity extends Activity { 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    String pass = "pass"; 

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // 2008-03-09T16:05:07 

    Date date = new Date(); 
    System.out.println(dateFormat.format(date)); 

    Calendar cal = Calendar.getInstance(); 

    String gettime = dateFormat.format(cal.getTime()); 
    System.out.println(gettime); 

    String Key = md5(pass + cal.getTime()); 
    System.out.println(Key); 

    // Log.e("Md5", gettime); 

    SendHttpGetRequest(Key, gettime); 

} 

private static String md5(String s) { 
    try { 

     // Create MD5 Hash 
     MessageDigest digest = java.security.MessageDigest 
       .getInstance("MD5"); 
     digest.update(s.getBytes()); 
     byte messageDigest[] = digest.digest(); 

     // Create Hex String 
     StringBuffer hexString = new StringBuffer(); 
     for (int i = 0; i < messageDigest.length; i++) 
      hexString.append(Integer.toHexString(0xFF & messageDigest[i])); 
     return hexString.toString(); 

    } catch (NoSuchAlgorithmException e) { 
     e.printStackTrace(); 
    } 
    return ""; 

} 

public void SendHttpGetRequest(final String mykey, final String mydt) { 

    class CheckLattery extends AsyncTask<String, Void, String> { 
     ProgressDialog pDialog; 

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

      pDialog = new ProgressDialog(MainActivity.this); 

      pDialog.setCancelable(false); 
      pDialog.show(); 
      pDialog.setContentView(R.layout.custom_progressdialog); 
     } 

     @Override 
     protected String doInBackground(String... params) { 

      HttpClient httpClient = getNewHttpClient(); 
      try { 

       HttpGet httpGet = new HttpGet(
         "************"); 
       httpGet.addHeader("key", mykey); 
       httpGet.addHeader("dt", mydt); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 

       System.out.println("httpResponse"); 
       InputStream inputStream = httpResponse.getEntity() 
         .getContent(); 
       InputStreamReader inputStreamReader = new InputStreamReader(
         inputStream); 
       BufferedReader bufferedReader = new BufferedReader(
         inputStreamReader); 
       StringBuilder stringBuilder = new StringBuilder(); 

       String bufferedStrChunk = null; 
       while ((bufferedStrChunk = bufferedReader.readLine()) != null) { 
        stringBuilder.append(bufferedStrChunk); 
       } 
       System.out.println("Returning value of doInBackground :" 
         + stringBuilder.toString()); 
       return stringBuilder.toString(); 

      } catch (ClientProtocolException cpe) { 
       System.out 
         .println("Exception generates caz of httpResponse :" 
           + cpe); 
       cpe.printStackTrace(); 
      } catch (IOException ioe) { 
       System.out 
         .println("Second exception generates caz of httpResponse :" 
           + ioe); 
       ioe.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 
      if (pDialog != null) { 
       pDialog.dismiss(); 
       pDialog = null; 
      } 

      Log.wtf("result", result + "res"); 

     } 
    } 
    CheckLattery latterychek = new CheckLattery(); 
    latterychek.execute(); 
} 

public HttpClient getNewHttpClient() { 
    try { 
     KeyStore trustStore = KeyStore.getInstance(KeyStore 
       .getDefaultType()); 
     trustStore.load(null, null); 

     SSLSocketFactory sf = new MySSLSocketFactory(trustStore); 
     sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

     HttpParams params = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

     SchemeRegistry registry = new SchemeRegistry(); 
     registry.register(new Scheme("http", PlainSocketFactory 
       .getSocketFactory(), 80)); 
     registry.register(new Scheme("https", sf, 443)); 

     ClientConnectionManager ccm = new ThreadSafeClientConnManager(
       params, registry); 

     return new DefaultHttpClient(ccm, params); 
    } catch (Exception e) { 
     return new DefaultHttpClient(); 
    } 
} 

}

在我的選擇我有問題頭部parameters.i不知道什麼是錯誤的..我第一次在httpget方法中使用頭參數 如果有人知道解決方案請幫助我謝謝

+0

同樣的請求與來自提琴手或郵遞員的靜態變量,你也得到404? –

回答

0

請參閱下面的代碼。如果GET方法意味着傳遞空字符串。

public ServiceHelper(Context context) { 
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
        .permitAll().build(); 
      StrictMode.setThreadPolicy(policy); 
      this.context = context; 

     } 

     public JSONObject jsonSendHTTPRequest(String requestData, 
       String requestURL, String requestType) { 
      try { 
       if (!Utilities.isConnectingToInternet(context)) { 
        JSONresponseText = new JSONObject(); 
        JSONresponseText.put(Constants.KEY_ERROR, 
          Constants.TOAST_INTERNET); 
       } else { 
        HttpURLConnection connection = null; 
        try { 
         Log.e("request data", requestData + Constants.EMPTY_STRING 
           + requestURL); 
         URL object = new URL(requestURL); 
         connection = (HttpURLConnection) object.openConnection(); 
         connection.setDoOutput(true); 
         connection.setDoInput(true); 
         connection.setRequestMethod(requestType); 
         connection.setRequestProperty(Constants.KEY_CONTENT_TYPE, 
           Constants.VALUE_CONTENT_TYPE); 
         connection.setRequestProperty(Constants.KEY_ACCEPT, 
           Constants.VALUE_CONTENT_TYPE); 
         connection.setRequestProperty(Constants.KEY_AUTHENTICATION, 
           Constants.VALUE_ENCODING_AUTHENTICATION); 

         if (requestType 
           .equalsIgnoreCase(Constants.REQUEST_TYPE_POST)) { 
          OutputStreamWriter streamWriter = new OutputStreamWriter(
            connection.getOutputStream()); 
          streamWriter.write(requestData); 
          streamWriter.flush(); 
         }else{ 
          requestURL = requestURL.replaceAll(" ", "%20"); 
         } 

         StringBuilder stringBuilder = new StringBuilder(); 
         if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
          InputStreamReader streamReader = new InputStreamReader(
            connection.getInputStream()); 
          BufferedReader bufferedReader = new BufferedReader(
            streamReader); 
          String response = null; 
          while ((response = bufferedReader.readLine()) != null) { 
           stringBuilder.append(response + "\n"); 
          } 
          bufferedReader.close(); 
          Log.d("Result Value ", stringBuilder.toString()); 
          jsonResultText = new JSONObject(
            stringBuilder.toString()); 
          return jsonResultText; 
         } else { 
          Log.e("Error = ", connection.getResponseMessage()); 
          return null; 
         } 
        } catch (Exception exception) { 
         Log.e("Error = ", exception.toString()); 
         return null; 
        } finally { 
         if (connection != null) { 
          connection.disconnect(); 
         } 
        } 
       } 
      } catch (Exception e) { 
       Log.e("Error = ", e.toString()); 
      } 
      return JSONresponseText; 
     } 
0

,如果你使用的HttpClient發佈的懇求,你可以使用HTTPGET設置標題爲您發佈,如果你使用HttpURLConnection的做到這一點,你應該在下面的代碼中使用:

HttpURLConnection connection = null; 
URL object = new URL("your url"); 
connection = (HttpURLConnection) object.openConnection(); 
connection.setRequestProperty("header name","header value"); 
如果運行