upload to a URL and set HttpURLConnection - Android Network

Android examples for Network:Network Connection

Description

upload to a URL and set HttpURLConnection

Demo Code


import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import android.content.Context;

public class Main{
    public static boolean uploadCall(Context context, String params,
            String requestMethod) {
        boolean isUpload = false;
        if (!HttpUtil.detect(context))
            return false;
        try {//from w w w .  j a v  a 2s .  c o m
            String strUrl = getURL() + "/" + requestMethod;
            URL url = new URL(strUrl);

            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.getOutputStream().write(params.getBytes());
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                Logger.d("NewworkUtil", "??????????????");
                isUpload = true;
            } else {
                Logger.d("NewworkUtil", "?????????????");
            }
        } catch (Exception e) {
            Logger.d("NewworkUtil", "??????????????" + e.getMessage());
        }
        return isUpload;
    }
    public static native String getURL();
}

Related Tutorials