POST方式向服务器提交数据报错

胡文武 发布于 2017/04/11 17:30
阅读 455
收藏 0

【Gopher China万字分享】华为云的Go语言云原生实战经验!>>>

我是做安卓的,今天写了个用POST方式向服务器提交数据,一直提交不了,代码也不报错,打印出来是这个java.lang.NumberFormatException:Invalid int: 8081
这个8081是我的服务器端口号,求大神解答,谢谢!!

加载中
0
annkee
annkee
post请求有多种,不贴代码不好看,这是数字格式转换异常
0
胡文武
胡文武
这是我的代码,帮我看一下,谢谢!!
public class HttpUtils {

    public static String submitPostData(String strUrlPath, Map<String,String> params,String encode){

        byte[] data = getRequestData(params,encode).toString().getBytes();//获得请求体

        try {
            URL url = new URL(strUrlPath);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);//设置连接超时时间
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

            httpURLConnection.setRequestProperty("Content-Length",String.valueOf(data.length));

            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data,0,data.length);
            outputStream.close();
            int response = httpURLConnection.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK){
                InputStream inputStream = httpURLConnection.getInputStream();

                return dealResponseResult(httpURLConnection.getInputStream(),encode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "err: "+e.getMessage().toString();
        }
        return "-1";
    }

    private static StringBuffer getRequestData(Map<String, String> params, String encode) {

        StringBuffer stringBuffer = new StringBuffer();
            try {
                for (Map.Entry<String,String> entry : params.entrySet()){
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(),encode))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }catch (Exception e){
                e.printStackTrace();
        }
        return stringBuffer;
    }

    private static String dealResponseResult(InputStream inputStream,String encode) {
        String resultData = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        if (inputStream != null) {
            try {
                while ((len = inputStream.read(data)) != -1) {
                    byteArrayOutputStream.write(data, 0, len);
                }
                resultData = new String(byteArrayOutputStream.toByteArray(),encode);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultData;
    }
}
public class MainActivity extends AppCompatActivity{

    private Button post_btn;
    private TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        result = (TextView) findViewById(R.id.result);
        post_btn = (Button) findViewById(R.id.btn);
        post_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                post_btn_OnClick(view);
            }
        });
    }

    private void post_btn_OnClick(View view){
        String strRecSmsMsg = "收短信测试";
        RecSmsToPost(strRecSmsMsg);
    }
    private void RecSmsToPost(String strRecSmsMsg){
        String strNowDateTime = getNowDateTime("yyyy-MM-dd|HH:mm:ss");

        Map<String,String> params = new HashMap<String, String>();
        params.put("shopId","371");
        params.put("advertAreaId","1");
//        params.put("mode","iisue");
//        params.put("call","shopService.qryAdvertList");
//        params.put("params","{\"advertAreaId\":\"1\",\"shopId\":\"371\"}\n");
//        params.put("version","1.0.0");


        String strUrlPath = "http://192.168.31.177:8081" + "DataTime=" + strNowDateTime;
        String strResult = HttpUtils.submitPostData(strUrlPath,params,"utf-8");
        result.setText(strResult);
    }
    private String getNowDateTime(String strFormat){
        if (strFormat == ""){
            strFormat = "yyyy-MM-dd HH:mm:ss";
        }
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
        return dateFormat.format(now);
    }
}
0
淘气的小猴子
淘气的小猴子
String strUrlPath = "http://192.168.31.177:8081" + "DataTime=" + strNowDateTime;

&DateTime...

胡文武
胡文武
这个是打印出现在的时间
0
zigzagroad
zigzagroad

URL=URI?queryString

URI与queryString之间要加?(问号),也就是 URI+?+queryString 才是完整的URL格式。

queryString的多个参数之间用&连接。

另外,你的上述代码封装是“不支持同时提交多个同名参数的”。

胡文武
胡文武
这个问题解决了 但我现在点击按钮 直接就停止运行
zigzagroad
zigzagroad
URL由URI与“可选的queryString”联合组成。当有queryString时,URI与queryString之间要有问号(?)。而你的程序中显然是缺少了问号的。
胡文武
胡文武
我这里面没有什么URL = URI 啊 能不能说详细点 我是个安卓菜鸟,还有要怎么才能同时提交多个数据呢
0
胡文武
胡文武

这是现在的代码 但运行点击按钮的时候直接停止运行

public class HttpUtils {

    public static String submitPostData(String strUrlPath, Map<String,String> params,String encode){

        byte[] data = getRequestData(params,encode).toString().getBytes();//获得请求体
        try {
            URL url = new URL(strUrlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);//设置连接超时时间
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

            httpURLConnection.setRequestProperty("Content-Length",String.valueOf(data.length));

            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);
//            outputStream.close();
            int response = httpURLConnection.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK){
                InputStream inptStream = httpURLConnection.getInputStream();

                return dealResponseResult(inptStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "err: "+e.getMessage().toString();
        }
        return "-1";
    }

    private static StringBuffer getRequestData(Map<String, String> params, String encode) {

        StringBuffer stringBuffer = new StringBuffer();
            try {
                for (Map.Entry<String,String> entry : params.entrySet()){
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(),encode))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }catch (Exception e){
                e.printStackTrace();
        }
        return stringBuffer;
    }

    private static String dealResponseResult(InputStream inputStream) {
        String resultData = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
            try {
                while ((len = inputStream.read(data)) != -1) {
                    byteArrayOutputStream.write(data, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        resultData = new String(byteArrayOutputStream.toByteArray());
        return resultData;
    }
}

 

public class MainActivity extends AppCompatActivity{

    private Button post_btn;
    private TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        result = (TextView) findViewById(R.id.result);
        post_btn = (Button) findViewById(R.id.btn);
        post_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                post_btn_OnClick(view);
            }
        });
    }

    private void post_btn_OnClick(View view){
        String strRecSmsMsg = "收短信测试";
        RecSmsToPost(strRecSmsMsg);
        openToast("提交测试完成");
    }
    private void RecSmsToPost(String strRecSmsMsg){
        String strNowDateTime = getNowDateTime("yyyy-MM-dd|HH:mm:ss");

        Map<String,String> params = new HashMap<String, String>();
//        params.put("shopId","371");
//        params.put("advertAreaId","1");
        params.put("mode","iisue");
        params.put("call","shopService.qryAdvertList");
        params.put("params","{\"advertAreaId\":\"1\",\"shopId\":\"371\"}\n");
        params.put("version","1.0.0");


        String strUrlPath = "http://192.168.31.177:8081" + "?DateTime=" + strNowDateTime;
        String strResult = HttpUtils.submitPostData(strUrlPath,params,"utf-8");
        result.setText(strResult);
    }
    private String getNowDateTime(String strFormat){
        if (strFormat == ""){
            strFormat = "yyyy-MM-dd HH:mm:ss";
        }
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
        return dateFormat.format(now);
    }
    //弹出消息
    private void openToast(String strMsg){
        Toast.makeText(this, strMsg, Toast.LENGTH_LONG).show();
    }
}
0
任重而道元
任重而道元
你int类型的产量是不是传成字符串了??感觉是这个的问题
0
Eric_林
Eric_林
String strUrlPath = "http://192.168.31.177:8081" + "DataTime=" + strNowDateTime;

这8081后不需要跟 /? 吗?你把URL打印出来,应该是规范

 

还是不行把异常贴出来

胡文武
胡文武
问题找到了 是android4.0之后要在子线程里面访问网络 但我不知道怎么用OkHttp,大神 给个qq嘛 帮我解决下问题嘛 谢谢!!!
0
Ronald9
Ronald9
太乱了,你要POST就POST,你的时间戳也别附加到url后面,当然如果你一定要这样,那也可以,我估计你的URL有问题,只是建议你,要么断点,要么2分法调试,
Ronald9
Ronald9
你可以先把完整URL直接在浏览器里试一试看看,
0
y
ylmotol7
明显没有加问号
返回顶部
顶部