HttpURLConnection访问网络

1、HttpURLConnection访问网络时实例化对象如下:

URL url = new URL("http://www.baidu.com");//获取地址
URLConnection connection = url.openConnection();

2、发送GET请求:默认发送的就是GET请求。
Android代码如下:
`

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText urlcontent;
    private TextView textcontent;
    private Button submit;
    private String result;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        urlcontent = (EditText) this.findViewById(R.id.urlcontent);
        textcontent = (TextView) this.findViewById(R.id.textcontent);
        submit = (Button) this.findViewById(R.id.submit);
        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if("".equals(urlcontent.getText().toString())){
                    Toast.makeText(getApplicationContext(), "请输入网址", Toast.LENGTH_SHORT).show();
                    return;
                }
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        send();
                        Message m = handler.obtainMessage();
                        handler.sendMessage(m);
                    }
                }).start();
            }
        });
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(result!=null){
                    textcontent.setText(result);
                    urlcontent.setText("");
                }
                super.handleMessage(msg);
            }
        };
    }
    //发送信息
    public void send(){
//      String urlEdit = urlcontent.getText().toString();
        String target="";
//      target = "http://192.168.1.100:8080/blog/index.jsp?aaaaacontent="
//                  +base64(urlcontent.getText().toString().trim());    //要访问的URL地址
        target = urlcontent.getText().toString();
        try {
            URL url = new URL(target);//获取地址
            URLConnection connection = url.openConnection();
            InputStreamReader in = new InputStreamReader(connection.getInputStream());//获取输入流
            BufferedReader breader = new BufferedReader(in);
            String inputLine = null;
            while((inputLine = breader.readLine())!=null){
                result+=inputLine+"\n";
            }
            in.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    //对字符串进行Base64编码
    public String base64(String content){
        try {
            content=Base64.encodeToString(content.getBytes("utf-8"), Base64.DEFAULT);   //对字符串进行Base64编码
            content=URLEncoder.encode(content); //对字符串进行URL编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();    //输出异常信息
        }
        return content;
    }
}


activity_main代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    >
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="http://www.baidu.com"
        android:id="@+id/urlcontent"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/submit"
        android:text="提交"
        />
    <ScrollView 
        android:id="@+id/scrollview"
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
        <TextView 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textcontent"
            />
    </ScrollView>
</LinearLayout>

`
3、发送POST请求:setRequestMethod(“POST”);需要判断是否响应成功,响应成功方可读取数据。
访问网站以http://www.baidu.com为例,所以可以读取到数据,写是无法写成功的。
以下代码有写的操作,步骤正确,只是无法写成功。可以自己搭建服务器代码。

通过以下方法设置相关内容
`
urlConn.setDoInput(true);//像连接中写入数据
urlConn.setDoOutput(true);//从连接中读取数据
urlConn.setUseCaches(false);//禁止缓存
urlConn.setInstanceFollowRedirects(true);//自动执行HTTP重定向
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置内容类型

`

Android代码如下:其他代码与GET一样,只更改了send()方法。
`
public void send(){
// String target = “http://192.168.1.100:8080/blog/index.jsp“;//要提交的目的地址
target = urlcontent.getText().toString();
URL url;
try {
url = new URL(target);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();//创建一个Http连接
urlConn.setRequestMethod(“POST”);//使用POST请求方式
urlConn.setDoInput(true);//像连接中写入数据
urlConn.setDoOutput(true);//从连接中读取数据
urlConn.setUseCaches(false);//禁止缓存
urlConn.setInstanceFollowRedirects(true);//自动执行HTTP重定向
urlConn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);//设置内容类型
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());//获取输出流
String param = “name=”+URLEncoder.encode(“lili”, “utf-8”)+”&content=”+URLEncoder.encode(“jiayou”, “utf-8”);
out.writeBytes(param);//将要传递的数据写入数据输出流
out.flush();//输出缓存
out.close();

        // 判断是否响应成功
        if(urlConn.getResponseCode() == HttpURLConnection.HTTP_OK){
            InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
            BufferedReader buffer = new BufferedReader(in);
            String inputLine = null;
            while((inputLine = buffer.readLine()) != null){
                result += inputLine+"\n"; 
            }
            in.close();
        }
        urlConn.disconnect();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值