post HTTP Request and set user agent - Android Network

Android examples for Network:HTTP Request

Description

post HTTP Request and set user agent

Demo Code


//package com.java2s;
import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Main {
    public static String postRequest(final String url,
            final String rawParams) throws Exception {

        FutureTask<String> task = new FutureTask<String>(
                new Callable<String>() {
                    @Override//w ww .ja  v  a 2  s .co m
                    public String call() {

                        PrintWriter out = null;

                        BufferedReader in = null;

                        String result = "";

                        try {

                            URL localurl = new URL(url);

                            URLConnection conn = localurl.openConnection();

                            conn.setRequestProperty("accept", "*/*");

                            conn.setRequestProperty("connection",
                                    "Keep-Alive");

                            conn.setRequestProperty("user-agent",
                                    "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");

                            conn.setDoOutput(true);

                            conn.setDoInput(true);

                            out = new PrintWriter(conn.getOutputStream());

                            out.print(rawParams);

                            out.flush();

                            in = new BufferedReader(new InputStreamReader(
                                    conn.getInputStream()));

                            String line;

                            while ((line = in.readLine()) != null) {
                                result += line;
                            }

                            return result;

                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if (out != null) {
                                    out.close();
                                }
                                if (in != null) {

                                    in.close();
                                }
                            } catch (Exception e2) {
                                e2.printStackTrace();
                            }
                        }
                        return null;

                    }
                });

        new Thread(task).start();
        return task.get();
    }
}

Related Tutorials