android使用标头发送HTTP GET请求

时间:2014-12-24 11:52:58

标签: android http-headers http-get

在我的Android应用中,我想要一个带有GET参数的网址并阅读回复。在请求中我必须添加两个头参数(键和dt).i写了一些代码,但我有404错误。这是我的来源

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();
    }
}

}

在我的选项中我在头参数中有问题。我不知道什么是错误的...我第一次在httpget方法中使用头参数 如果有人知道解决方案,请帮助我谢谢

2 个答案:

答案 0 :(得分:0)

请参考下面的Code.If 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;
        }

答案 1 :(得分:0)

如果你使用httpClient发布请求,你可以使用HttpGet设置你发布的标题,如果你使用HttpURLConnection来做,你应该使用下面的代码:

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