HttpClient提交數據

1.AndroidManifest.xml添加網絡訪問權限

 

<uses-permission android:name="android.permission.INTERNET"/>

 

2.在web項目中新建servlet

 

package cn.com.servlet;

 

import java.io.IOException;

 

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class LoginServlet extends HttpServlet {

 

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//服務器接受統一編碼iso-8859-1,然後獲取字符串時轉化為utf-8

String name = new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8");

String password = request.getParameter("password");

System.out.println("name:"+name);

System.out.println("password:"+password);

if(name.equals("張三")&&password.equals("123")){

//往瀏覽器寫字符串

response.getOutputStream().write("HttpClienget方式登錄成功".getBytes("utf-8")); //寫到瀏覽器的編碼是utf-8

}

else{

response.getOutputStream().write("HttpClienget方式登錄失敗".getBytes("utf-8")); //寫到瀏覽器的編碼是utf-8

}

}

 

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//doGet(request, response);

//服務器接受統一編碼iso-8859-1,然後獲取字符串時轉化為utf-8

String name = new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8");

String password = request.getParameter("password");

System.out.println("name:"+name);

System.out.println("password:"+password);

if(name.equals("張三")&&password.equals("123")){

//往瀏覽器寫字符串

response.getOutputStream().write("HttpClienpost方式登錄成功".getBytes("utf-8")); //寫到瀏覽器的編碼是utf-8

}

else{

response.getOutputStream().write("HttpClientpost方式登錄失敗".getBytes("utf-8")); //寫到瀏覽器的編碼是utf-8

}

}

        

}

 

 

 

 

3.文件佈局

 

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

 

    <EditText

        android:id="@+id/name"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="輸入用戶名" 

        android:text="張三"

        />

    <EditText

        android:id="@+id/password"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="輸入密碼" />

    

    <Button

        android:id="@+id/button"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="ClientGet提交"

        android:onClick="onClick3"

         />

    <Button

        android:id="@+id/button"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="ClientPost提交"

        android:onClick="onClick4"

         />

    

 

</LinearLayout>

 

 

 

4.MainActivity.java

package com.example.get;

 

import java.io.UnsupportedEncodingException;

 

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

 

public class MainActivity extends Activity {

private EditText name,password;

private final int SUCCESS=1;

private Handler handler = new Handler(){

 

@Override

public void handleMessage(Message msg) {

if(msg.what==SUCCESS){

String result = (String) msg.obj;

if(result!=null){

Toast.makeText(MainActivity.this, result, 1).show();

}else{

Toast.makeText(MainActivity.this, "登陸失敗", 1).show();

}

}

}

};

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        

        name = (EditText) findViewById(R.id.name);

        password = (EditText) findViewById(R.id.password);

        

      

    }

 

  

   /**

    * clientget提交

    * @param view

    */

   public void onClick3(View view){

   final String loginName = name.getText().toString();

   final String loginPasswor = password.getText().toString();

   new Thread(){

 

@Override

public void run() {

final String result=LoginService.loginClientGet(loginName, loginPasswor);

if(result!=null){

//在主線程上運行

runOnUiThread(new Runnable() {

@Override

public void run() {

Toast.makeText(MainActivity.this, result, 1).show();

}

});

}

}

       

       }.start();

   

   }

   

   

   public void onClick4(View view){

   final String loginName = name.getText().toString();

   final String loginPasswor = password.getText().toString();

   new Thread(){

 

@Override

public void run() {

final String result=LoginService.loginClientPost(loginName, loginPasswor);

if(result!=null){

//在主線程上運行

runOnUiThread(new Runnable() {

@Override

public void run() {

Toast.makeText(MainActivity.this, result, 1).show();

}

});

}

}

       

       }.start();

   

   }

    

}

 

5 業務類 LoginService .java

 

package com.example.get;

 

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.List;

 

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

 

public class LoginService {

/**

 * clientget方式提交

 * @param name

 * @param password

 * @return

 */

public static String loginClientGet(String name,String password){

try {

//打開瀏覽器

HttpClient client = new DefaultHttpClient();

//輸入地址

String path = "https://10.162.0.171:8080/WebGet/LoginServlet?name="+URLEncoder.encode(name)+"&password="+URLEncoder.encode(password);

HttpGet get = new HttpGet(path);

//敲回車

HttpResponse response=client.execute(get);

int code=response.getStatusLine().getStatusCode();

if(code==200){

InputStream is=response.getEntity().getContent();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len=0;

//將輸入流不斷的讀,並放到緩沖區中去。直到讀完

if((len=is.read(buffer))!=-1){

//將緩沖區的數據不斷的寫到內存中去。

baos.write(buffer, 0, len);

}

byte[] b=baos.toByteArray();

is.close();

baos.close();

return new String(b,"utf-8");

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return null;

}

return null;

}

/**

 * clientpost方式提交

 * @param name

 * @param password

 * @return

 */

public static String loginClientPost(String name,String password){

try {

//打開瀏覽器

HttpClient client = new DefaultHttpClient();

//輸入地址

String path="https://10.162.0.171:8080/WebGet/LoginServlet";

HttpPost post = new HttpPost(path);

//添加地址參數

List<NameValuePair> parameters = new ArrayList<NameValuePair>();

parameters.add(new BasicNameValuePair("name", name));

parameters.add(new BasicNameValuePair("password", password));

post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));

//敲回車

HttpResponse response=client.execute(post);

int code=response.getStatusLine().getStatusCode();

if(code==200){

InputStream is=response.getEntity().getContent();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len=0;

//將輸入流不斷的讀,並放到緩沖區中去。直到讀完

if((len=is.read(buffer))!=-1){

//將緩沖區的數據不斷的寫到內存中去。

baos.write(buffer, 0, len);

}

byte[] b=baos.toByteArray();

is.close();

baos.close();

return new String(b);

}

} catch (Exception e) {

// TODO Auto-generated catch block

return null;

}

return null;

}

 

}

發佈留言