2014-12-24 4 views
2

내 Android 앱에서 GET 매개 변수가 포함 된 URL을 요청하고 응답을 읽으려고합니다. 요청에서 내 소스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(); 
    } 
} 

} 내 옵션

내가 문제의가있다 나는 몇 가지 코드를 작성 .I (키와 DT) 두 개의 헤더 매개 변수를 추가해야하지만 난 404 error.this이 헤더 매개 변수. 내가 무엇을 잘못 생각하는지 모르겠다. 처음으로 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

당신이 요청을 게시 세션 객체를 사용하는 경우 게시 당신이 그것을 할 HttpURLConnection의를 사용하는 경우, 당신은 당신이 코드 아래 사용해야합니다, 헤더를 설정하는 HttpGet을 사용할 수 있습니다

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