android网络要的POST方法

//Post 提交数据方法:   
- (void)post
{
    NSString *postString = [NSStringstringWithFormat:@"         {\\"userName\\":\\"%@\\",\\"userPass\\":\\"%@\\",\\"version\\":\\"1.0\\"}",self.userField.text,self.passwordField.text]; 
    NSLog(@"%@",postString);
   //一般转化称UTF-8,这里服务器需要ASCII
    NSData* postData = [postStringdataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES];
   NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease];
    [requestsetURL:[NSURLURLWithString:@"http://lib.wap.zol.com.cn/test/login.php"]];
    [requestsetCachePolicy:NSURLRequestUseProtocolCachePolicy];
    [requestsetTimeoutInterval:100.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
   // 应该是application/x-www-form-urlencoded,但对方服务器写成了appliction/x-www-form-urlencoded,告诉服务器是一个表单提交数据方式
    [requestsetValue:@"appliction/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];    
    //得到提交数据的长度
    NSString* len = [NSString stringWithFormat:@"%d", [postData length]];
    //添加一个http包头告诉服务器数据长度是多少
    [requestsetValue:len forHTTPHeaderField:@"Content-Length"];
    [NSURLConnectionconnectionWithRequest:request delegate:self];
}

//POST接收数据方法:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"didReceiveResponse");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData");

    [self.mutabledataappendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");  
    self.strUser = [[NSStringalloc]initWithData:self.mutabledataencoding:NSASCIIStringEncoding];
}
//该片段来自于http://outofmemory.cn
package com.jredu.helloworld.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.jredu.helloworld.R;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

public class HttpUrlConnectionPostActivity extends AppCompatActivity {
    WebView webView;
    Button button;
    TextView success;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_url_connection_post);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpUrlConnectionPost();
                    }
                }).start();
            }
        });
    }

    public void HttpUrlConnectionPost(){
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http//:www.baidu.com");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(5*1000);
            urlConnection.setReadTimeout(5*1000);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Connection","Keep-Alive");
            urlConnection.setRequestProperty("Charset","utf-8");
            urlConnection.setRequestProperty("Content-type","application/x-www-form-urlencode");
            String a = "page = 1&num = 10";
            OutputStream os = urlConnection.getOutputStream();
            os.write(a.getBytes());
            os.flush();
            os.close();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
                InputStream is = urlConnection.getInputStream();
                StringBuilder sb = new StringBuilder();
                byte[] bytes = new byte[1024];
                int i = 0;
                while ((i = is.read(bytes)) != -1){
                    sb.append(new String(bytes,0,i,"utf-8"));
                }
                is.close();
                Message message = handler.obtainMessage(1,sb.toString());
                handler.sendMessage(message);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && msg.what == 1){
                String s = (String) msg.obj;
                String data = new String(s.getBytes(), Charset.forName("utf-8"));
                webView.getSettings().setDefaultTextEncodingName("utf-8");
                webView.getSettings().setJavaScriptEnabled(true);
                webView.loadDataWithBaseURL(null,data,"text/html","utf-8",null);
                Toast.makeText(getApplication(),"post请求成功!",Toast.LENGTH_SHORT).show();
            }
        }
    };
}

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图